Filling Arrays With A For Loop?
Mar 15, 2015
I am having trouble conceptualizing how to fill arrays. I understand that I can declare one and number it's elements, and it stores values of a certain data types. I don't really understand beyond that. Like how I would fill and use data in it.
I can be more specific with an assignment I have for school, but need to get started understanding how to fill arrays with data and then how to use that data.
View Replies
ADVERTISEMENT
Dec 13, 2014
I am just starting to use ArrayLists for the first time. I was wondering if there is a way to automatically fill ArrayLists with a for loop.
For example:
ArrayList<Integer> numberList = new ArrayList<Integer>();
int limit;
Integer starter = new Integer(1);
[Code].....
I need to make an ArrayList with numbers 1-limit, inclusive, and rather than doing this with a regular array I am doing it with an ArrayList because I will need the remove() method later. Anyway, my question was if there is a way to fill an ArrayList with a for loop. My code doesn't work at the moment, giving this error: Array type expected; found: 'java.util.ArrayList<java.lang.Integer>'
View Replies
View Related
Dec 25, 2014
I am attempting to grab stock prices for an array of different stock tickers. In my code, I iterate through the array of stock tickers and at the same time, grab the stock prices from an API. Then, I store the stock prices into a new array and attempt to display the new array.
For example: An array element may contain 'AAPL' as a stock ticker. The for loop enters this element into the URL which links to an API, grabs the stock prices, stores it into a temporary variable. Then it stores the value (the stock price) of that temporary variable in to a new array. Then the new array will attempt to print out this stock price along with all the other stock prices.
Here is my code:
public static void getStock(String[] tickers) {
for (i = 0; i < tickers.length; i++) {
try {
URL url = new URL("http://query.yahooapis.com/v1/public
[Code] .....
The above code works fine if I am printing the stock prices from inside the for loop. And I can see why, it enters and prints the new stock price in the new array through each loop.
My problem is, I do not know how to access the new array (stockOutput) outside of the for loop, or how to display its contents outside of the for loop.
View Replies
View Related
Jul 24, 2014
i have a row of int JTextfields and i want to get a running total of the sum of all boxes in the last total JTextfield, as the user types.I understand its an actionlistener but whats the best way of doing it. What the action to listen out for?
View Replies
View Related
Oct 19, 2014
So I an assignment in Java to write a code which will randomly populate squares in a Tic Tac Toe Board. I pretty much have it I think, but I cannot get the 'O' to appear on the board, some squares will be blank. We were told to use the Random utility to generate the squares. I am attaching the .gif's which are used. Here is my code:
import javax.swing.*;
import java.awt.*;
import java.util.Random;
public class LandryTicTacToe extends JFrame
{
/**
*
*/
private static final long serialVersionUID = -8781512780135301721L;
private final int HEIGHT = 450;//Set value for Height
private final int WIDTH = 500;//Set value for Width
private static JButton [] button = new JButton[9];//Declare array of Buttons
[Code] .....
[attachment=37084:TicTac0.gif][attachment=37085:TicTacX.gif]
Instructions Given to me:
Display a frame that contains nine labels, arranged like a Tic Tac Toe board. A label may display an image icon for X, an image icon for O, or nothing. Display images randomly in each label. Use the Random class to generate 0, 1, or 2, which corresponds to displaying an X image, an O image, or nothing.
Attached image(s)
View Replies
View Related
Aug 9, 2014
I realized that I was not filling the array with anything but now I'm having issues filling it correctly. It's only filling the array with three of the user inputs ....
import java.util.Scanner;
public class DriverSort {
public static void main(String[] args) {
Scanner scan =new Scanner(System.in);
Sorter sorter = new Sorter();
int choice; // variable which says which sorting algorithm to use
[Code] .....
View Replies
View Related
Mar 4, 2014
I have run into a bit of a head scratcher, at least to me. I am building multiple rectangles using double precision. I had to switch from int to double due to another issue that requires decimal places. Now, my fillRect (last line in the code section I posted) is causing an error as it only wants to work with int.
public void draw(Graphics2D g2) {
// check that sizes are above 0
if ((rectWidth <= 0) || (rectHeight <= 0))
[Code]....
View Replies
View Related
Jun 6, 2014
I am trying to create an array filled with the object Card. It keep throwing the exception that the "deck is empty". I am not sure why that's happening because the code for filling the array seems fine.
public class Deck {
private Card[] deck;
private CardPile cardPile;
private int numCards;
public Deck() throws InvalidDataException{
this.deck = new Card[52];
[Code] .....
View Replies
View Related
Feb 5, 2015
I have a problem with the size of my scrollPane. It won't fill the space in the JPanel.
is there a way to let the scrollPane fill the whole space?
View Replies
View Related
Apr 18, 2015
Here is the code: I believe the issue is in the nest for loop with I use
f1.length
But I want to not use the individual sizes I put in, something more suitable so I don't have to change the the values everywhere I may need to.
public class ForestFireDemo {
public static void main(String[] args) {
Forest[][] f1;
f1 = new Forest[10][5];
for(int i =0 ; i < f1.length; i++) {
[Code] ....
View Replies
View Related
Jun 28, 2014
I mainly would like to know is a int[4][4] or a int [4*4] is more efficient to use. Which takes more storage? Which requires more to process? that kind of stuff.
View Replies
View Related
Feb 7, 2015
I am passing input from the user to a method that will initialize an array of the data (scores in this case). The method is filling the entire array with the last input value.
array initializer method
Java Code:
public static float[] inputAllScores(float validScore) {
float[] diverScores = new float[7];
for (int i = 0; i < diverScores.length; i++) {
diverScores[i] = validScore;
}
return diverScores;
} mh_sh_highlight_all('java');
[Code] .....
View Replies
View Related
Jan 27, 2015
I am trying to print a loop inside an array of a greater size than the loop itself. Like for example I have an array of size 7 but it has only 3 elements.
int[] array=new int[7]
array[0]=2;
array[1]=3;
array[2]=4;
now what I want to do is print these three numbers in a loop so that my array[3]=2;array[4]=3;array[5]=4 ...... till the last one. Also the array could be any size and not just 7.
View Replies
View Related
Feb 25, 2014
Here's the code: it's while loop inside a for loop to determine the proper length of a variable:
for (int i = 0; i < num; i++) {
horse[i]=new thoroughbred();
boolean propernamelength = false;
while (propernamelength==false){
String name = entry.getUserInput("Enter the name of horse "
[code]....
I was just wondering what was going on here -- I've initialized the variable, so why do I get this message? (actually the carat was under the variable name inside the parentheses.
View Replies
View Related
Nov 2, 2014
I have everything else working. My problem is that when i type "quit" to close the outer loop. It still runs the inner loop. The National Bank manager wants you to code a program that reads each clients charges to their Credit Card account and outputs the average charge per client and the overall average for the total number of clients in the Bank.
Hint: The OUTER LOOP in your program should allow the user the name of the client and end the program when the name entered is QUIT.In addition to the outer loop, you need AN INNER LOOP that will allow the user to input the clients charge to his/her account by entering one charge at a time and end inputting the charges whenever she/he enters -1 for a value. This INNER LOOP will performed the Add for all the charges entered for a client and count the number of charges entered.
After INNER LOOP ends, the program calculates an average for this student. The average is calculated by dividing the Total into the number of charges entered. The program prints the average charge for that client, adds the Total to a GrandTotal, assigns zero to the Total and counter variables before it loops back to get the grade for another client.Use DecimalFormat or NumberFormat to format the numeric output to dollar amounts.
The output of the program should something like this:
John Smith average $850.00
Maria Gonzalez average $90.67
Terry Lucas average $959.00
Mickey Mouse course average $6,050.89
National Bank client average $1,987.67
Code:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String name = "";
int charge = 0;
int count = -1;
int total = 1;
int grandtotal = 0;
int average = 0;
[code]....
View Replies
View Related
Mar 8, 2014
How to convert this program from a while loop to a for loop.
import java.util.Scanner;
public class LongDivision {
public static void main(String arguments[]){
Scanner input = new Scanner(System.in);
System.out.println("Enter the dividend: ");
[Code] ....
View Replies
View Related
Feb 17, 2014
How do I convert my for loop below to a while and do while loop?
for(int a=1;a<=9;a++){
for(int b=1;b<=a;b++){
System.out.print(a);
}
System.out.println();
[Code] .....
View Replies
View Related
Feb 9, 2015
I am trying to make a program add values from a loop. So what its supposed to do is search through tokens on an imported file. The file lists State, Capital, and then capital population. Then take the population string, turn it into numbers, and then do stuff with the numbers. First I'm supposed to find the Highest and lowest population of the places in the file (which I did without problem), but the finally thing is I'm supposed to add each found population to the last so I can find the average of the populations.
I just cannot seem to grasp how to do that. I THINK I'm supposed to some how store the given value into a variable, but how do I get that variable to add to the new value?
like...?
Get token -> a
b = a
c = a + b
or wait no.....
Java Code :
import java.io.*;
import java.util.Scanner;
public class CapPopS
{
public static void main(String[] args) throws IOException
{
File stateCAP = new File("state-capital-2004population.txt");
if (!stateCAP.exists())
[Code] ....
View Replies
View Related
Apr 23, 2015
I'm wonder about the issue of constructor for arrays. Let say I have a class tablica, and one component int[] tab. If I get it right until now tab is nothing more than empty reference to some unexisting array?
import java.util.Random;
class tablica{
int[] tab;
tablica (){ // i wish it was constructor
[code]....
Then, I'm trying to build the constructor for class tablica. What can be the parameter of such constructor? Is it fields of array? It is simple forf for basic variable
- I liken values defined in constructor with those global defined in class. But how to do it with array component tab.
If I create array object in main method then how can I use this constructor?
View Replies
View Related
Sep 19, 2014
How do i increase the size of a 2D array from 2X2 to 4X4 where only the boundary elements are zeroes and the rest of them remain the same?
View Replies
View Related
Jan 28, 2015
In the program below I populated three arrays: student id, name, and GPA. The findStudent() method attempts to match users input with the input stored in the studentID array using an if/ else statement. When I use the if/ else statement the else always executes regardless if the IDs match? I am trying to get JOptionPane.showMessageDialog(null, "Incorrect entry"); to print only if the IDs don't match.
Java Code:
//FILE: StudentIDArray.java
import javax.swing.*; //Used for the JOption dialog boxes
import java.util.*; //Used for Scanner input
public class StudentIDArray {
boolean nameFound = true;
final int numOfElements = 2; //Final int to control to loop for data
[code]....
View Replies
View Related
Aug 22, 2014
I'm working on a side project, which will eventually hopefully be a Pokedex, and I've just been going to it at the end of every chapter and using the stuff I've learned to work on it.So I just read chapter 3, which is all about variables and teaches how to use arrays.
my question is, does an array have to be declared inside a method? Because I'm trying to create an array inside a class without any methods and without the main, and I continuously get errors. Here's a quick working of my code that won't compile.
class blah {
blah a[] = new blah[7];
a[0] = new blah();
}
The error message focuses on a[0] = new blah(); Telling me the 0 should be a ], the = is an illegal start of type, so on and so forth. The program compiles completely fine if it's within a method, like this:
class blah {
void a() {
blah a[] = new blah[7];
a[0] = new blah();
}
}
Or if I have public static void main (String[]args); But I'm trying to practice working outside of main.So does an array have to be within a method,
View Replies
View Related
Nov 22, 2014
I have created a class and a matrix of doubles (or at least, I think I have, that's partly what I want to verify).I need to return the values of the array,Here is my class:
public class example{
double[][] Position=new double[2][11];
double calculate(){
for (int time=0;time<=10;time=time+1){
Position[1][time]=time;
Position[2][time]=time+1;
double A=Position[2][time];
return A;
}
}
}
I am getting the error: "This method must return a result of type double", though to me it looks like I am returning double (A).
View Replies
View Related
Sep 21, 2014
So im making this ghost game where i display an 8x8 filled with 0s and a randomly generator five 1s in there I can get it to display 0s and add 1s, however sometimes the 1s that are randomly generated sometimes go on the same spot making it look like there are only four 1s. How would i go about fixing that?
package Grade12;
import java.util.Random;
public class Ghost {
public static void main(String[] args) {
Random generator = new Random();
int gameboard [][] = new int [8][8];
int randomx, randomy, counter = 0, sum = 0;
for(int row = 0; row < 8; row++){
for(int col = 0; col < 8; col++){
(gameboard[row][col]) = 0;
}
[code]...
View Replies
View Related
Mar 4, 2014
The assignment goes like this...Write a Payroll class that uses the following arrays as fields:
employeeID - An array of seven integers to hold employee identification numbers. The array should be initialized with the following numbers:
5658845452012578951228777541
845127713028507580489
hours - An array of seven integers to hold the number of hours worked by each employee.payRate - An array of seven doubles to hold each employee's hourly pay rate.wages - An array of seven doubles to hold each employee's gross wages.The class should relate the data in each array through the subscripts.
For example, the number in element 0 of the hours array should be the number of hours worked by the employee whose identification number is stored in element 0 of the employeeID array. That same employee's pay rate should be stored in element 0 of the payRate array. In addition to the appropriate accessor and mutator methods, the class should have a method that accepts an employee's identification number as an argument and returns the gross pay for that employee.Demonstrate the class in a complete program that displays each employee number and asks the user to enter that employee's hours and pay rate. It should then display each employee's identification number and gross wages.Input Validation: Do not accept negative values for hours or numbers less than 6.0 for a pay rate.
My problem with this program is that everytime I try to print the employee ID's or the wages, I get hashcode or something like it (#[I1a77cdc or something like that). I tried using the toString method, but it lists all of the values, when I'm trying to display one at a time. Here is the code for the class:
// moduleArray class
public class moduleArray {
final int NUM_EMPLOYEES = 7;
int[] employeeID = {5658845, 4520125, 7895122, 8777541, 8451277, 1302850, 7580489};
int[] hours = new int[NUM_EMPLOYEES];
[code]...
This is the demo program to list the ID's. I've been messing with it for some time, and right now I just want it to display values.
import java.util.Scanner;
public class moduleArrayDemo {
public static void main(String[] args) {
final int NUM_EMPLOYEES = 7;
int[] ID = new int[NUM_EMPLOYEES];
[code]...
View Replies
View Related
Dec 14, 2014
Okay, so the assignment was creating a word search for the given array. I've created all the code necessary, but I've ran into trouble. This problem occurs with the Up-Forward, Up-Backward, Down-Forward, and Down-Backward sections. If I only set one of these to run, it works. But if I have all 4 set at the same time, it errors out on the first one that runs.
public class P_WordSearch {
public static void main(String[] args) {
char[][] puzzle = {
{'B','O','O','G','S','R','O','W','I','N','G'},
{'E','B','L','G','N','I','M','M','I','W','S'},
{'L','C','E','A','T','I','P','U','P','I','S'},
{'C','M','I','N','C','A','X','Y','O','S','N'},
[Code] ....
View Replies
View Related