I want to flip 5 coins as a group - 1024 times and count how many tails i get. However i am getting ArrayIndexOutOfBoundsException: 4 error.
Is this because j in the second loop is not reset when the first loop runs its first time? If so, how would i go about this then?
public class Q2 {
public static void main(String[] args) {
int totalTails, totalHeads;
int coin[];
coin = new int[4];
totalHeads = 0;
totalTails = 0;
for (int i = 0; i < 1024; i++) {
for (int j=0; i<5; j++){
coin[j] = 1 + (int) (Math.random() * (2 - 1 + 1));
if (coin[j] == 1) {
totalHeads++;
}
else {
totalTails++;
}
}
}
System.out.println("Number of tails were obtained = " + totalTails);
System.out.println("Number of heads were obtained = " + totalHeads);
}
}
for (int j=0; i<5; j++){
It should be j<5
coin = new int[4];
It should be int[5]
Change this line:
for (int j=0; i<5; j++){
To this line:
for (int j=0; j<4; j++){
You are going out of bounds on coin
It would be even better if you use length property. Like th
for (int j=0; j<coin.length; j++){
please change for (int j=0; i<5; j++) to for (int j=0; j<5; j++) and your code should work fine.
Related
How can I find the total sum for each two dimensional array row? I'm completely stuck...
public static void main(String[] args) {
int [][] grid = new int [10][10];
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
grid[i][j] = (int)(Math.random()*99);
}
}
for(int i = 0; i < 10; i++) {
for(int j = 0; j < 10; j++) {
System.out.print("1.");
System.out.printf("%5d ", grid[i][j]);
}
System.out.println();
}
}
My current output is:
How can I show the total sum for each row in the end of the row and show column numbers
For the sum of a row, this should do. In a similar way within the i loop, if you need to count the column as well;
for(int i = 0; i < 10; i++) {
int jSum = 0;
for(int j = 0; j < 10; j++) {
jSum += grid[i][j];
System.out.print("1.");
System.out.printf("%5d ", grid[i][j]);
}
System.out.printf(" %5d", jSum);
System.out.println();
}
On the column numbering:
Either you just pust put a static print in the beginning (like print "1 2 3 4..."), or you put the following with the j loop:
if (i == 0) System.out.printf("%5d ", j); // only prints in first loop / row - print 1,2,3,4,5....
I have to print the following numbers using nested loops, and I kinda have an idea how, but not how to execute it.
000111222333444555666777888999
000111222333444555666777888999
000111222333444555666777888999
My code so far is something like:
public class opgave_2 {
public static void main(String[] args) {
final int first = 3;
final int second = 3;
final int third = 9;
for (int i = 0; i <= first ; i++) {
for (int j = i; j <= second; j++) {
for (int k = j; k <= third; k++) {
System.out.print(i);
}
}
}
}
}
You should proceed by steps to resolve such problem.
First, you want to print a number 3 times :
int myNumber = 0;
for(int i=0; i<3; i++) {
System.out.print(myNumber);
}
Second, you want to repeat it 9 times and your number to vary from 0 to 9 (seems like an index of loop) :
for(int myNumber=0; myNumber<=9; myNumber++) {
for(int i=0; i<3; i++) {
System.out.print(myNumber);
}
}
Third, you want to display this line 3 times :
for(intj=0; j<3; j++) {
for(int myNumber=0; myNumber<=9; myNumber++) {
for(int i=0; i<3; i++) {
System.out.print(myNumber);
}
}
System.out.println(""); //new line
}
What about something like this:
for (int i = 0; i < 3; i++) {
for (int j = 0; j <= 9; j++) {
System.out.printf("%1$s%1$s%1$s", j);
}
System.out.println();
}
Which uses 2 nested loops. The first to print the line 3 times, and the second to print the numbers per line
you can use a loop, that loops 3 times. in that you put a loop that prints every number from 0 to 9 3 times in a row within the same line
for(int a = 0; a < 3; a++){
for(int i = 0; i < 10; i++){
System.out.print(i+""+i+""+i);
}
System.out.println(); //for the new line
}
or
for(int a = 0; a < 3; a++){
for(int i = 0; i < 10; i++){
System.out.print(i);
System.out.print(i);
System.out.print(i);
}
System.out.println(); //for the new line
}
this should do
This is my current code:
public static void main(String[] args) {
int [][] twoD = new int [5][5];
/*for(int i = 0; i<5; i++){
for(int j = 0; j<5; j++){
System.out.print(twoD[i][j] + "");
}
}*/
}
}
I can't seem to do it. I got confused and I removed the part of testing w/commenting. Just ignore that.
I am aiming to get a two dimensional array like this:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
However, I just don't get it. How can I get that result? I'm a beginner at java.
First, you need to populate the array with data, and you forgot System.out.println for each row of the array.
int [][] twoD = new int [5][5];
// populate array with data
for(int i = 0; i<5; i++){
for(int j = 0; j<5; j++){
twoD[i][j] = (j+1)*(i+1);
}
}
// print result
for(int i = 0; i<5; i++){
for(int j = 0; j<5; j++){
System.out.print(twoD[i][j]);
System.out.print(" ");
}
System.out.println();
}
You have to populate the data as well:
int[][] arr = new int [5][5];
for(int i = 0; i<5; i++){
for(int j = 0; j<5; j++){
arr[i][j] = (j+1)*(i+1);
}
}
And the code to print would be:
for(int i = 0; i<5; i++){
for(int j = 0; j<5; j++){
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
You are doing fine, you just need to put line jump System.out.println(); every time the second for ends
for(int i = 0; i<5; i++){
for(int j = 0; j<5; j++){
System.out.print(twoD[i][j] + " ");
}
System.out.println();
}
You are on the right track, that for loop will print out the array like that, all you need to do is print a new line character after finishing the for(j) loop. But, at least in the snippet you posted, you aren't actually doing any assignments, so there aren't any values in your array to print, Java will initialize all ints to zero for you.
The array doesn't just automatically populate with incrementing integers, rather each cell of the array will automatically initialized to 0, you have to set the values you want the array to contain. You can use the concept of your testing class to do this if you wish, just set each cell of the 2D array to a certain value. After that, you can print out the array, making sure to print a each row of the array on a new line. For instance:
public static void main(String[] args) {
int [][] twoD = new int [5][5];
int increment = 1;
for(int i = 0; i<5; i++){
for(int j = 0; j<5; j++){
twoD[i][j] = increment++;
}
}
for(i = 0; i<5; i++){
for(j = 0; j<5; j++){
System.out.print(twoD[i][j] + " ");
}
System.out.println();
}
}
The first set of nested for loops will set each of the cells of the 2D array to the incremented integers you want (note increment++ will first set the cell to the value increment currently is, then add one to the variable). The second set of nested for loops will print out the array as you desire.
refer this code
int[][] twoD = new int[5][5];
// add values to array
for (int i = 0; i < 5; i++) {
int val = 1;
val = val + i;
for (int j = 0; j < 5; j++) {
twoD[i][j] = val * (j + 1);;
}
}
// Print array
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
System.out.print(twoD[i][j] + " ");
}
System.out.println();
}
as others pointed out you need to print it nicely to see the pattern, i and j are indices of your array. However, I see that you have a nice pattern so just running two loops won't solve the problem.
Maybe something like this would help (not giving exact answer intentionally)
int [][] twoD = new int [5][5];
int i;
// initialize
int c = 1; int j = 0;
for(c=1; c<5; c++) {
for( i = 1; i<=5; i++){
twoD[i-1][c-1] = c*c*i; twoD[c-1][i-1]=c*c*i;
}
}
for( i = 0; i<5; i++) {
for( j = 0; j<5; j++) {
System.out.print(twoD[i][j]);System.out.print(" " );
}
System.out.println("\n");
}
Im doing some personal work, and I am using this array that I thought of, but I cant figure out whats the array is after the code stops running.
int cnt = 0;
int[][] numarray = new int[2][3];
for(int i = 0; i < 3; i++) {
for(int j = 0; j< 2; j++) {
numarray[j][i] = cnt;
cnt++;
}
}
I am pretty sure that it ends at [2][1] but I am not 100% sure of it
Just tried this code:
int cnt = 0;
int[][] numarray = new int[2][3];
for(int i = 0; i < 3; i++) {
for(int j = 0; j< 2; j++) {
numarray[j][i] = cnt;
cnt++;
System.out.print(numarray[j][i]+" ");
}
System.out.println("");
}
and got this result:
0 1
2 3
4 5
The 'cnt' is incremented by 1 for each iteration. That's why you have 0,1,2,3,4,5.
Also learn how to use debugger in an IDE, you can then explore the value of i, j, cnt by yourself.
why don't you try this?
int cnt = 0;
int[][] numarray = new int[2][3];
for(int i = 0; i < 3; i++) {
for(int j = 0; j< 2; j++) {
numarray[j][i] = cnt;
System.out.println(String.format("array[%d[%d]=%d",j,i,numarray[j][i]));
cnt++;
}
}
you can iterate the array after code finish
for(int i = 0; i < 2; i++) {
for(int j = 0; j< 3; j++) {
System.out.print(numarray[i][j]+" ");
}
System.out.println();
}
summary: cnt is incremented by 1 for each iteration in the inner for loop.
cnt is being incremented by 1 i.e. cnt++ is same as cnt = cnt + 1;
so count values increment from 0 i.e. 0,1,2,3,4,5... Also note, the value of cnt is assigned to the array being created, where you have numarray[j][i] = cnt;
You can simply printout the value using System.out.println(cnt);
I wrote the following code in JAVA.
package threed;
import java.util.Scanner;
public class Threed_Array {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int b1,b2,b3;
System.out.print("Enter the number of elements in 1st bracket->");
Scanner sc=new Scanner(System.in);
b1=sc.nextInt();
System.out.print("Enter the number of elements in 2nd bracket->");
b2=sc.nextInt();
System.out.print("Enter the number of elements in 3rd bracket->");
b3=sc.nextInt();
int threedarray[][][]=new int[b1][b2][b3];
for(int i=1; i<=b1; i++)
{
for(int j=1; i<=b2; j++)
{
for(int k=1; i<=b3; k++)
{
System.out.print("Enter element->");
threedarray[i][j][k]=sc.nextInt();
}
}
}
for(int i=1; i<=b1; i++)
{
for(int j=1; i<=b2; j++)
{
for(int k=1; i<=b3; k++)
{
System.out.print(" "+threedarray[i][j][k]);
}
}
}
}
}
I am getting ArrayIndexOutOfBoundsException for this code. This is showing in the line:
threedarray[i][j][k]=sc.nextInt();
Can anybody help me out where the error is occurring? Thank you.
You should always start at index 0, it is the index of the first element of your array:
for(int i=0; i<b1; i++)
{
for(int j=0; j<b2; j++)
{
for(int k=0; k<b3; k++) {
System.out.print("Enter element->");
threedarray[i][j][k]=sc.nextInt();
}
}
}
for(int i=0; i<b1; i++)
{
for(int j=0; j<b2; j++)
{
for(int k=0; k<b3; k++)
{
System.out.print(" "+threedarray[i][j][k]);
}
}
}
furthermore make the check with < not <=
With the last loop you access the array element n+1 where n is the size of that array. Thats the reason for the exception.
I'd say the conditions in your loops are not correct :
for(int i=1; i<=b1; i++)
{
for(int j=1; i<=b2; j++)
{
for(int k=1; i<=b3; k++)
{
it should be :
for(int i=1; i<=b1; i++)
{
for(int j=1; j<=b2; j++)
{
for(int k=1; k<=b3; k++)
{
Also, you should start at 0 in each of them.
I think you want j and k in the 2 inside for loops instead of i. Also, arrays in Java start in index 0, so it should look like this:
for(int i=0; i<b1; i++)
{
for(int j=0; j<b2; j++)
{
for(int k=0; k<b3; k++)
{
...
}
}
}
Arrays in Java are zero-based, try to iterate from 0 to b1-1:
for(int i=0; i<b1; i++)
{
for(int j=0; i<b2; j++)
{
for(int k=0; i<b3; k++)
{
System.out.print("Enter element->");
threedarray[i][j][k]=sc.nextInt();
}
}
}
[b1][b2][b3]
You create an array using the inputs b1,b2,b3
The array created has length of bx but subscripts from 0 to bx-1. Hence you must loop from 0 to bx-1
Indices start at 0, not 1. Start your three for loops at 0 and iterate to one less than the number provide:
for(int i = 0; i < b1; i++)
{
for(int j = 0; i < b2; j++)
{
for(int k = 0; i < b3; k++)
{
System.out.print(" "+threedarray[i][j][k]);
}
}
}
Apart from the array index problem (see Stefan Beike's answer), you could you an ArrayList.
This would avoid having to ask the user for the number of elements you want to have in your matrix.
Still if you want to keep primitive arrays, you could use System.arrayCopy to reallocate to a greater size array.
The problem here is that you are starting the loop from 1 till the b1,b2,b3 respectively. Array indexes start from 0 not from 1 and ends at the size of the array - 1. So to fix your code you need to modify the code to be the following:
for(int i = 0; i < b1; i++) {
for(int j = 0; j < b2; j++) {
for(int k = 0; k < b3; k++) {
System.out.print("Enter element->");
threedarray[i][j][k]=sc.nextInt();
}
}
}
More generally if you don't know the length/size of the array you are looping on, you can make the loop more generally to be less than the array length. So it would be i < threedarray.length and j < threedarray[i].length and k < threedarray[i][j].length.
The key idea is that the array indexing starts from 0 and ends at its size/length - 1, so to get the last element you access array[array.length-1] and to access the first element you access array[0]
Hope this answers your question.