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
Related
New to java and am trying to create a program/method that will take an int array, and return another int array but it replaces the values of the indexes with the value of the elements. (Example {2,1,3} will return {0,0,1,2,2,2}
public static void main(String[] args) {
int[] pracArray = {2, 1, 3};
int sum = 0;
for (int i = 0; i < pracArray.length; i++)
{
sum = sum + pracArray[i];
}
System.out.println("Amount of array indexes: " + sum);
int[] newArray = new int[sum];
System.out.println(Arrays.toString(pracArray));
for (int i = 0; i < pracArray.length; i++)
{
for (int j = 0; j < pracArray[i]; j++)
{
newArray[j] = i;
}
}
System.out.println(Arrays.toString(newArray));
}
}
Currently I am getting [2,2,2,0,0,0]. I have tried changing the how many times each for loop iterates with no avail. I have also tried to make the elements of newArray equal to a counter ( int count = 0; and having count++ in the for loop) since the values of the new array will always be 0 - however many runs.
Given the length of your array is 3, your outer 'i' loop is iterating through the values 0,1,2. That means your inner 'j' loop never writes to index 3,4,5 (hence why they are 0 in the output), and why the first 3 indexes are set to '2' (2 is the last indexed processed in the 'i' loop). Try this instead...
int h = 0;
for (int i = 0; i < pracArray.length; i++)
{
for (int j = 0; j < pracArray[i]; j++)
{
newArray[h] = i;
h++;
}
}
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
}
}
}
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 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
I want to make a loop on Two-dimensional array in Java.
How I do that? I wrote:
for (int i = 0; i<=albums.size() - 1; i++){
for (int j = 0; j<=albums.size() - 1; j++){
But it didn't work. Thanks.
Arrays have a read-only field called length, not a method called size. A corrected loop looks like this:
for(int i = 0; i < albums.length; i++ ) {
for (int j = 0; j < albums[i].length; j++) {
element = albums[i][j];
You have to recognize that a 2-D array is just an array whose element type happens to be another array. So the i loop iterates over each element in albums (which is an array) and the j loop iterates over that child array (with a potentially different size).
A more transparent way would be like this:
String[][] albums;
for(int i = 0; i < albums.length; i++ ) {
String[] childArrayAtI = albums[i];
for (int j = 0; j < childArrayAtI.length; j++) {
String element = childArrayAtI[j];
}
}
Try this if you are working with Java 1.5+:
for(int [] album : albums) {
for(int albumNo : album) {
System.out.print(albumNo + ", ");
}
System.out.println();
}
First of all, a two-dimensional array looks like this in Java:
int[][] albums = new int[10][10];
Now, for iterating over it:
for (int i = 0; i < albums.length; i++) {
for (int j = 0; j < albums[i].length; j++) {
int value = albums[i][j];
}
}