I'm a complete newbie when it comes to Java and I've been working on a simple program which creates a grid with multiple slots. Each slot has an X and a Y value and is stored in an ArrayList called "s".
Here's my code:
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
s.add(new Slot(j, i));
}
}
Height and width are user inputed values.
It's a simple loop within a loop and essentially it should work but instead of creating multiple slots with the values 0, 0, 1,0 2, 0 3, 0 and so forth until it should increase the Y axis by one it never increases the Y-value. Instead after doing the first loop it will go back to 0, 0 instead of 0, 1.
Also here's the how it's supposed to print the values:
for (int i = 0; i <= height; i++) {
for (int j = 0; j <= width; j++) {
System.out.print(s.get(j));
}
System.out.println("");
}
Example:
0,0
1,0
2,0
3,0
...
9,0
0,0 (instead of 0,1)
My question is why on earth doesn't my first loop ever increase the value of i? Sorry if I sound like an idiot, I'm a total noob.
You have a problem in your printing function.
I don't know what s is but:
for (int i = 0; i <= height; i++) {
for (int j = 0; j <= width; j++) {
System.out.print(s.get(j));
}
System.out.println("");
}
Get objects based on j value only. You need to get objects based on i and j in order to get all values.
Or you can just iterate over all objects in s (if s is a Collection):
for (Slot sl : s) {
System.out.println(sl);
}
The j value only ranges between 0 and width - 1 so s.get(j) is only going to access the first width items in s. Try this instead:
for (int i = 0; i <= height; i++) {
for (int j = 0; j <= width; j++) {
System.out.print(s.get(i * width + j));
}
System.out.println("");
}
Or you could just iterate over the contents of s and not use nested for loops for the retrieval.
You don't need the nested loop when printing, Just iterate over the ArrayList:
for(Slot slot : s )
{
System.out.println(slot);
}
Your problem is the print function. Just iterate over s and print each slot:
for (Slot slot : s) {
System.out.println(slot);
}
As it is implemented now, you print items in s from indexes 0 -> width over and over again, height times.
Also, learn about the for-each loop, available from Java 5 instead of using get(index):
Oracle Tutorial
The problem is you are storing height * width elements in a one dimensional array - ArrayList but retreiving only width number of elements.
Instead of arraylist of Slot for s, use two dimensional array.
Slot[][] s = new Slot[width][height];
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
s[j][i](new Slot(j, i));
}
}
for (int i = 0; i <= height; i++) {
for (int j = 0; j <= width; j++) {
System.out.print(s[j][i]);
}
System.out.println("");
}
you only print j from the same place every time
Related
Here is the code when I haven't stored in a list. This gets what I want to display in different textfields but I want it to be shorter so I want to loop it.
//"answerStoration.retrieveDataChoices(i,TB)" is a function from other class that returns an arraylist;
quizAnswer1store.setText(answerStoration.retrieveDataChoices(1,TB).get(0));
quizAnswer2store.setText(answerStoration.retrieveDataChoices(1,TB).get(1));
quizAnswer3store.setText(answerStoration.retrieveDataChoices(1,TB).get(2));
quizAnswer4store.setText(answerStoration.retrieveDataChoices(1,TB).get(3));
quizAnswer1store2.setText(answerStoration.retrieveDataChoices(2,TB).get(0));
quizAnswer2store2.setText(answerStoration.retrieveDataChoices(2,TB).get(1));
quizAnswer3store2.setText(answerStoration.retrieveDataChoices(2,TB).get(2));
quizAnswer4store2.setText(answerStoration.retrieveDataChoices(2,TB).get(3));
quizAnswer1store3.setText(answerStoration.retrieveDataChoices(3,TB).get(0));
quizAnswer2store3.setText(answerStoration.retrieveDataChoices(3,TB).get(1));
quizAnswer3store3.setText(answerStoration.retrieveDataChoices(3,TB).get(2));
quizAnswer4store3.setText(answerStoration.retrieveDataChoices(3,TB).get(3));
I stored it in a List "quizAnswerSTORE" and I tried to loop but doesnt work.
int k = 0;
for(int i = 0; i<quizAnswerSTORE.size(); i++){
for(int j = 1; j < 11; j++){
while(k<4){
quizAnswerSTORE.get(i).setText(answerStoration.retrieveDataChoices(j,TB).get(k));
}
}
}
The expected result is to diplay different values from a database in different 40 txtfields. Because each time the loop values increments, it rolls through my database with different values. J variable represents the id in my database. And the K is an index in the values taken in the arrayList returned by retrieveDataAnswers function from a four columned database.
There you go. I hope you can solve this.
You can use mod to control maximun int values, for example i % 10 can't take values more than 10.
Example:
public class Main {
public static void main(String[] args) {
int j = 1;
int k = 0;
for(int i = 0; i < 40; i++) {
System.out.println("quizAnswerSTORE"+i+".setText(answerStoration.retrieveDataChoices("+j+",TB).get("+k+"));");
k = (k + 1)%4;
if( k == 0) {
j = (j+1) % 11;
}
}
}
}
output:
quizAnswerSTORE0.setText(answerStoration.retrieveDataChoices(1,TB).get(0));
quizAnswerSTORE1.setText(answerStoration.retrieveDataChoices(1,TB).get(1));
quizAnswerSTORE2.setText(answerStoration.retrieveDataChoices(1,TB).get(2));
quizAnswerSTORE3.setText(answerStoration.retrieveDataChoices(1,TB).get(3));
quizAnswerSTORE4.setText(answerStoration.retrieveDataChoices(2,TB).get(0));
quizAnswerSTORE5.setText(answerStoration.retrieveDataChoices(2,TB).get(1));
quizAnswerSTORE6.setText(answerStoration.retrieveDataChoices(2,TB).get(2));
quizAnswerSTORE7.setText(answerStoration.retrieveDataChoices(2,TB).get(3));
quizAnswerSTORE8.setText(answerStoration.retrieveDataChoices(3,TB).get(0));
quizAnswerSTORE9.setText(answerStoration.retrieveDataChoices(3,TB).get(1));
quizAnswerSTORE10.setText(answerStoration.retrieveDataChoices(3,TB).get(2));
quizAnswerSTORE11.setText(answerStoration.retrieveDataChoices(3,TB).get(3));
...
quizAnswerSTORE38.setText(answerStoration.retrieveDataChoices(10,TB).get(2));
quizAnswerSTORE39.setText(answerStoration.retrieveDataChoices(10,TB).get(3));
Try to be consistent with your indentation and line up closing brackets '}' with their corresponding statement.
The first problem I see with this code is that k is never incremented inside the while loop so it will always have the same value and loop forever. The second problem I see is that k is not reset after the while loop so when it goes through the loop the first time (and is correctly incremented) it will stay at a value of 4 and the loop will be skipped every time after that.
I'm not sure what you're trying to achieve (I could use some more information or a sample output) but to begin with you can correct the loop error by changing the while loop to a for loop like so.
for (int i = 0; i < quizAnswerSTORE.size(); i++) {
for (int j = 1; j < 11; j++) {
for (int k = 0; k < 4; k++) {
quizAnswerSTORE.get(i).setText(answerStoration.retrieveDataChoices(j,TB).get(k));
}
}
}
Alternatively, if you wanted to keep the while loop, you could so it like so.
for (int i = 0; i < quizAnswerSTORE.size(); i++) {
for (int j = 1; j < 11; j++) {
int k = 0; // Set k inside the 2nd loop and it will reset to 0 after the while loop
while(k < 4) {
quizAnswerSTORE.get(i).setText(answerStoration.retrieveDataChoices(j,TB).get(k));
k++; // Shorthand for k += 1 which is shorthand for k = k + 1
}
}
}
int[][] grid = new int[10][10];
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
// fill in
}
}
This is what I have so far. I know I need to add in Math.Random, then set X = 0 and O = 1. I'm just very lost and confused. I'm in no way a good java coder and for me this is too advanced.
char[][] grid = new char[10][10];
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
grid[i][j] = "XO".charAt((int)Math.round(Math.random()));
}
}
String#charAt() gets a character by the index. (So 0 returns X and 1 returns O)
Math.random() returns a random Double between 0 and 1, and with Math.round() you round that number to the nearest whole number. (So either 0 or 1) which is used to give to the charAt() as parameter.
You do still need to cast the outcome of Math.round() as an int because it will return a long.
The question is:
Create a method display2DArray().
a) Inside the method, declare a 2D array that will hold the following integers:
{10,20} {11,21}
{15,25} {17,28}.
b) Display this information using two for loops.
public static void display2DArray()
{
int[][] arrays = new int[][]
{
{10, 20}, {11,21}, {15,25}, {17,28}
};
for(int i = 0; i < 3; i++)
{
for(int j = 0; i < 1; j++)
{
System.out.println(arrays[i][j]);
}
}
}
This is what ive come up with, but its not correct.
Can someone tell me what i need to be doing?
You are almost there!
Few things:
1) Typo - In your inner for loop, you are using an "j" instead of "i".
2) The same "j" must be j<=1 OR j<2 because you have 2 columns i.e. 2 elements in each sub-array. So the indexes will be 0 and 1.
3) In your outer for loop, you are using i<3. Since you have 4 rows i.e. 4 sub arrays, your indexes will be 0,1,2,3. So you need to use i<=3 OR i<4.
4) You can print an empty line in the outer for-loop for a better display.
for(int i = 0; i <= 3; i++) // Since you have 4 rows, indexes would be 0,1,2,3
{
for(int j = 0; j <= 1; j++) // Since you have 2 columns, indexes would be 0,1
{
System.out.print(arrays[i][j]+","); // Print each row i.e. sub-array
}
System.out.println(""); // Print an empty line after each row
}
This gives you the output:
10,20,
11,21,
15,25,
17,28,
In your second for loop, you have "i < 1" instead of "j < 1"
Use j in second array
public static void display2DArray()
{
int[][] arrays = new int[][]
{
{10, 20}, {11,21}, {15,25}, {17,28}
};
for(int i = 0; i < 4; i++)
{
for(int j = 0; j < 2; j++)
{
System.out.println(arrays[i][j]);
}
}
}
Also the boundaries were wrong
Your Problem with the inner loop the you used . You used i instead of J. So, Your loop will not give you the result as you Expected.
for(int i = 0; i < 3; i++)
{
for(int j = 0; j <= 1; j++) //use j instead of i here.
{
System.out.println(arrays[i][j]);
}
}
Thanks
for(int i = 0; i <= 3; i++)
{
for(int j = 0; j <= 1; j++)
{
System.out.println(arrays[i][j]);
}
}
1.) second for loop condition check is j< 1 not i< 1
2.) first for loop condition check is i<=3
I am having trouble creating multiple arrays with a loop in Java. What I am trying to do is create a set of arrays, so that each following array has 3 more numbers in it, and all numbers are consecutive. Just to clarify, what I need to get is a set of, let's say 30 arrays, so that it looks like this:
[1,2,3]
[4,5,6,7,8,9]
[10,11,12,13,14,15,16,17,18]
[19,20,21,22,23,24,25,26,27,28,29,30]
....
And so on. Any help much appreciated!
Do you need something like this?
int size = 3;
int values = 1;
for (int i = 0; i < size; i = i + 3) {
int[] arr = new int[size];
for (int j = 0; j < size; j++) {
arr[j] = values;
values++;
}
size += 3;
int count = 0;
for (int j : arr) { // for display
++count;
System.out.print(j);
if (count != arr.length) {
System.out.print(" , ");
}
}
System.out.println();
if (i > 6) { // to put an end to endless creation of arrays
break;
}
}
To do this, you need to keep track of three things: (1) how many arrays you've already created (so you can stop at 30); (2) what length of array you're on (so you can create the next array with the right length); and (3) what integer-value you're up to (so you can populate the next array with the right values).
Here's one way:
private Set<int[]> createArrays() {
final Set<int[]> arrays = new HashSet<int[]>();
int arrayLength = 3;
int value = 1;
for (int arrayNum = 0; arrayNum < 30; ++arrayNum) {
final int[] array = new int[arrayLength];
for (int j = 0; j < array.length; ++j) {
array[j] = value;
++value;
}
arrays.add(array);
arrayLength += 3;
}
return arrays;
}
I don't think that you can "create" arrays in java, but you can create an array of arrays, so the output will look something like this:
[[1,2,3],[4,5,6,7,8,9],[10,11,12,13...]...]
you can do this very succinctly by using two for-loops
Quick Answer
==================
int arrays[][] = new int[30][];
for (int j = 0; j < 30; j++){
for (int i = 0; i < (j++)*3; i++){
arrays[j][i] = (i++)+j*3;
}
}
the first for-loop tells us, via the variable j, which array we are currently adding items to. The second for-loop tells us which item we are adding, and adds the correct item to that position.
All you have to remember is that j++ means j + 1.
Now, the super long-winded explanation:
I've used some simple (well, I say simple, but...) maths to generate the correct item each time:
[1,2,3]
here, j is 0, and we see that the first item is one. At the first item, i is also equal to 0, so we can say that, here, each item is equal to i + 1, or i++.
However, in the next array,
[4,5,6,7,8,9]
each item is not equal to i++, because i has been reset to 0. However, j=1, so we can use this to our advantage to generate the correct elements this time: each item is equal to (i++)+j*3.
Does this rule hold up?
Well, we can look at the next one, where j is 2:
[10,11,12,13,14...]
i = 0, j = 2 and 10 = (0+1)+2*3, so it still follows our rule.
That's how I was able to generate each element correctly.
tl;dr
int arrays[][] = new int[30][];
for (int j = 0; j < 30; j++){
for (int i = 0; i < (j++)*3; i++){
arrays[j][i] = (i++)+j*3;
}
}
It works.
You have to use a double for loop. First loop will iterate for your arrays, second for their contents.
Sor the first for has to iterate from 0 to 30. The second one is a little less easy to write. You have to remember where you last stop and how many items you had in the last one. At the end, it will look like that:
int base = 1;
int size = 3;
int arrays[][] = new int[30][];
for(int i = 0; i < 30; i++) {
arrays[i] = new int[size];
for(int j = 0; j < size; j++) {
arrays[i][j] = base;
base++;
}
size += 3;
}
I'm creating an array with ones and threes as the values for my indexes. I have twos to represent my borders. I've written four for loops to set up borders for my array. They all seem to work except for the for loop that creates the border for the right side.
value: 5
222222
213133
231133
211131
231331
222222
//Creates the border indexes for the cells represented by the value 2
for (int top = 0; top < cells.length; top++)
cells[0][top] = 2;
for (int bottom = 0; bottom < cells.length; bottom++)
cells[cells.length-1][bottom] = 2;
for (int left = 0; left < cells.length; left++)
cells[left][0] = 2;
//for some reason, this code doesn't do anything
for (int right = 0; right < cells.length; right++)
cells[right][cells.length] = 2;
// Creates the first generation of cells randomly
for (int i = 1; i <m; i++)
{
for (int j = 1; j < m; j++)
{
double CellCreate = Math.random();
if (CellCreate > .5)
{
cells[i][j] = 1;
}
else
{
cells[i][j] = 3;
}
}
}
//Prints the cells
for (int x = 0; x < cells.length;x++)
{
for (int y = 0; y < cells.length; y++)
{
System.out.print(cells[x][y]);
}
System.out.println();
}
You forgot to subtract 1 from cells.length:
for (int right = 0; right < cells.length; right++)
cells[right][cells.length-1] = 2;
Also, there is one thing iteresting here. The original loop didn't fail with an ArrayOutOfBoundsException, so it is highly likely that there is something awry going on at declaring your array too. I should have failed, if the array was properly defined. You should post that too... It seems, that you declared your rows in the array to have cells.length+1 elements
Otherwise, this is a classic loop ending problem, instead of cells.length in
cells[right][cells.length] = 2;
you should use cells.length-1
for (int right = 0; right < cells.length; right++)
cells[right][cells.length-1] = 2;
Other notes:
It is wise to always use the curly brackets to enclose the blocks of loops and if conditions:
//for some reason, this code doesn't do anything
for (int right = 0; right < cells.length; right++) {
cells[right][cells.length-1] = 2;
}
This way it will be less likely you get into a "no-loop" situation like this:
/**** BAD!!! *****/
for(...); // note the ; !!! That ends the loop block
doSomething(); //this will be done only once!
/**** BAD!!! *****/