I'm creating a project using java, but i have an error. I have created a method to generate some results to an array, but when i use it i don't get the results that I'm looking for. Please help me on this, here is my code.
public static String[] getYear(){
String[] w = new String[6];
int z = 0;
for(int x = 7;x<7;x++)
{
w[z] = String.valueOf(x);
z = z++;
}
return w;
This is how my combobox code looks:
com_year.addItem(form_student.getYear());
When I'm using it in a combobox the result I get is this:
[Ljava.lang.String;#1073463
But I need to get this:
1
2
3
4
5
6
Can u please help me on this.
You for loop condition is incorrect. This
for(int x = 7;x<7;x++)
Starts at 7 which is not less than 7 so the loop never runs.
I think you wanted
for (int x = 0; x < w.length; x++)
Also, your output is the default toString() from Object (Array doesn't override it). You can use Arrays.toString(arr) instead.
Your problem is with the line for(int x = 7; x < 7; x++). It reads that x = 7, which isn't less than 7, so it skips over the whole for loop. Try replacing x = 7 with x = 1.
Also, instead of displaying the string (that's where your're getting the weird numbers and symbols), you need to be displaying the string's contents. Try something like
for (int myInteger : q)
{
System.out.println(myInteger);
}
Related
good afternoon! hi all! 1st time posting
for my assignment we are filling arrays using arithmetic and nested for loops. i've done a complete filling of a 2D array before using prime numbers, although i think i'm messing up somewhere..
when doing the line int priorNum = arr[r-1][c]; (see full code below) i run into an exception. i am trying to overwrite other lines in my array with this new equation, but must i be stopped by this utmost unchivalrous java error.
the error: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 10
my array: int[][] arrayDimension = new int[10][6];
public static void populate2D (int[][] arr) {
//hardcode in values first :)
//and then peek up one row, but you can't go above the original row
arr[0][1] = 10;
arr[0][2] = 100;
arr[0][3] = 500;
arr[0][4] = 1000;
arr[0][5] = 5000;
int count = 0;
//for each row..
for (int r = 0; r < arr.length; r++) { //for each row
for ( int c = 0; c < arr[r].length; c++) { //for each column
arr[r][0] = count;
//never navigate out of bounds
//row 0 is where we're at.. how to populate further rows..?
int priorNum = arr[r-1][c];
int nextNum = priorNum * 2;
arr[r][c] = nextNum;
//can't look back .. SO go UP one.. which is r - 1 goes back one.. and then the length goes - 1
//when c is - peek UP a row < and enter last column.. ^
}
count++;
}
}
i left in some notes that i wrote if you can understand what i'm trying to go for :)
i can also offer this printArray method i wrote for any testing you'd like to try!
public static void print2DArray(int[][] arr) {
for ( int r = 0; r < arr.length; r++) {
for ( int c = 0; c < arr[r].length; c++) {
System.out.print(arr[r][c] + "\t");
}
System.out.println();
}
}
}
thank you for any replies / assistance! everyone here seems very nice, i could not find my type of question that deals with my answer so i felt bad about posting hehe
The problem I can see is that in the first iteration when int priorNum = arr[r-1][c]; gets executed, r = 0, as specified by your outer for loop.
So you are basically trying to access an element of your 2D array using a negative index, which will result in an ArrayIndexOutOfBoundException being thrown.
You could adopt an if statement that will handle the first iteration so that you will not access a prior index.
You could also look at the Array access section of the following article:
https://docs.oracle.com/javase/specs/jls/se7/html/jls-10.html
Hope this helped.
I am working on a sudoku game and I am using the method of creating a solved puzzle and then "digging holes" to get the puzzle that is displayed to the user. For some reason, the testingPuzzle array is being reset to the numbers array every time it goes through the loop. It is true that the testingPuzzle array should be set to the numbers array originally, but it should be edited one spot at a time every time it goes through the loop and have a bunch of zeroes in it after a few iterations. Here is the loop itself:
do{
x = Math.abs(rand.nextInt() % 9);
y = Math.abs(rand.nextInt() % 9);
takeaway_num = testingPuzzle[x][y];
testingPuzzle[x][y] = 0;
} while (arraysEqual(solvePuzzle(testingPuzzle), numbers));
SolvePuzzle is a method that solves the given puzzle as parameters and returns that solved puzzle. So basically arraysEqual(solvePuzzle(testingPuzzle), numbers)checks to see if testingPuzzle is solvable
I am setting the testingPuzzle array equal to the numbers array before the do while loop. It looks like this:
int[][] testingPuzzle = new int[9][9];
for(int y = 0; y < 9; y++){
for(int x = 0; x < 9; x++){
testingPuzzle[x][y] = numbers[x][y];
}
}
Just so you know numbers is the sodoku answer that was generated in a previous method.
I am using my own method for testing if the arrays are equal, called "arraysEqual because I thought .equals() was the problem originally. Here is the method I am using for this:
private static boolean arraysEqual(int[][] a, int[][] b){
for(int y = 0; y < 9; y++){
for(int x = 0; x < 9; x++){
if(a[x][y] != b[x][y]){
return false;
}
}
}
return true;
}
I'm not really sure why the testingPuzzle Array is being set to the same as the numbers array at the end of each loop. I think it could have something to do with passing the actual array vs. a copy of it to a method that takes in an array but I'm not sure how that works in java.
I was learning how to sort arrays with different types of value holders. I tried to sort an array with Strings, but it comes up with the error message, Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
at SortingArrays.main(SortingArrays.java:50)
There aren't any errors the compiler found, but it comes up with this. The array with numbers worked fine, but the strings didn't. Here is my code.
import java.util.Arrays;
public class SortingArrays {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] aryNums;
aryNums = new int[6];
aryNums[0] = 7;
aryNums[1] = 89;
aryNums[2] = 45;
aryNums[3] = 234;
aryNums[4] = 2;
aryNums[5] = 75;
Arrays.sort(aryNums);
int i;
for (i = 0; i < aryNums.length; i++) {
System.out.println(aryNums[i]);
}
String[] aryStrings;
aryStrings = new String[5];
aryStrings[0] = "I have no idea what I'm doing.";
aryStrings[1] = "Should I know what I'm doing?";
aryStrings[2] = "I guess not.";
aryStrings[3] = "There's my boss.";
aryStrings[4] = "Whoop, he's looking. Hide!";
Arrays.sort(aryStrings);
int x;
for (x = 0; x < aryStrings.length; x++) {
System.out.println(aryStrings[i]);
}
}
}
You are getting runtime exception. ArrayIndexOutOfBoundsException means you are trying to access array beyond its capacity with what its defined.
Problem is with this code:
for (x = 0; x < aryStrings.length; x++){
System.out.println(aryStrings[i]);
^^
}
You are using i as index instead of x. Here i (after your print statements) would be 6 in your case and your array can hold 5 elements which start with 0 and ends with 5.
At the very end of your program:
System.out.println(aryStrings[i]);
i = 6, of course it out of bounds
What you need is:
System.out.println(aryStrings[x]);
i after your first loop is 6.
so here
for (x = 0; x < aryStrings.length; x++){
System.out.println(aryStrings[i]); // i here is 6 but there are 5 elements in aryStrings
}
use x in this loop not i
As other commenters have said, the problem is with your iterating variable.
But to completely avoid this problem, use a for-each loop.
As Joshua Bloch says in Effective Java, 2nd Edition (Item 46):
// The preferred idiom for iterating over collections and arrays
for (int aryNum : aryNums) {
System.out.println(aryNum);
}
Or better in Java 8:
Arrays.stream(aryNums).forEach(System.out::println);
You're using i instead of x in the second print statement
Change the index in x
System.out.println(aryStrings[x]);
As the other answers have stated, by the time you reach your second loop, i is equal to a higher integer than your String array has indices.
Another way to fix your issue is to reset the value of i:
int x;
i = 0;//re-initialize
for (x = 0; x < aryStrings.length; x++) {
System.out.println(aryStrings[i]);
}
However, this defeats the purpose of your x variable.
As a rule of thumb, I'd keep your incrementer local to your loop to prevent problems like this arising:
//declare x in the loop
for (int x = 0; x < aryStrings.length; x++) {
System.out.println(aryStrings[x]);
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
public class mdar {
public void cont(){
Random rand = new Random();
int con = 100;
int multi[][]=new int [con][6];
for(int x = 0;x<multi.length;x++){
for(int y = 0;y<multi[x].length;y++){
int temp = rand.nextInt(9);
multi[x][y] = multi[x+1][temp]; //this line is going bad
}
}
for(int i=0;i<multi.length;i++){
System.out.print("contester "+multi[i]);
for(int j=0;j<multi[i].length;j++){
System.out.println(" has "+multi[i][j]+" ");
}
System.out.println();
}
}
}
I deleted my old project and so i was trying to remake it and i can't figure it out anymore :S
Could someone help me out here?
The second dimention of multi is 6;
int multi[][]=new int [con][6];
However you call anything up to 8 on that second dimention
int temp = rand.nextInt(9);
multi[x][y] = multi[x+1][temp]; //temp could be between 0 and 8 from the random function
As such you get an array index out of bounds, in your case temp was 7.
Addtionally your loop goes between 0 and multi[x].length-1
for(int y = 0;y<multi[x].length;y++){
But you call multi[x+1] which will at the end of the loop be one larger that the largest index of multi, but you'll hit this exception after the other one (99% of the time)
multi[x][y] = multi[x+1][temp];
I think you meant to write
multi[x][y] = temp;
//This would set multi[x][y] to a random int in the range [0,8] (inclusive)
instead of
multi[x][y] = multi[x+1][temp]; //this line is going bad
//This will assign the int value at multi[x+1][temp] to the variable multi[x][y]
There are 2 things wrong with this:
1) x is a for loop counter in range [0,multi.length) [inclusive, exclusive)
for(int x = 0;x<multi.length;x++)
x+1 is outside the bounds of the array
2) temp is a random int in range [0,8] [inclusive, inclusive]
int temp = rand.nextInt(9);
however the multi array is defined with a 2nd dimension size of 6 (valid locations multi[x][0] through multi[x][5])
int multi[][]=new int [con][6];
The random variable temp will be outside of the valid range 3/9 times (for 6, 7, 8), therefore you will encounter this error 33% of the time that nextInt(9) is called. Since it is called many times in a single call to cont() you will almost never have an execution that runs without error, however, it is still logically incorrect code whether it executes with or without error.
without an idea of what the code is supposed to do, it hard for us to give a solution. The error is quite clear. See in the last iteration of your outer loop x = multi.length - 1. So when you ask for multi[x+1][temp] you are asking for multi[multi.length] which is out of bounds since multi goes from [0 to multi.length-1].
In addition to that int temp = rand.nextInt(9) will also cause an out of bounds exception if it returns values 6,7 or 8, since the second dimension of multi must be in the range [0 to 5]
Again without an idea of what needs to be done, I can't know if the solution i propose below does what you want to do:
for(int x = 0;x<multi.length - 1;x++){
for(int y = 0;y<multi[x].length;y++){
int temp = rand.nextInt(multi[x+1].length);
multi[x][y] = multi[x+1][temp];
}
}
When your
int temp = rand.nextInt(9);
gives value as "7". You are getting this error. Debug and find.
You geting out of the length of the array, try to do this:
if(x+1 < multi.length)
{
multi[x][y] = multi[x+1][temp];
}
multi[x][y] = multi[x+1][temp];
at the end of loop x+1 making it.
You are declaring your 2D array with second dimension 6:
int multi[][]=new int [con][6];
Valid index of second dimension will be in range 0..5.
But then you access it with random number like 7 which is out of bounds:
int temp = rand.nextInt(9);
multi[x][y] = multi[x+1][temp]; //this line is going bad
int temp = rand.nextInt(9);
System.out.println(temp);
multi[x][y] = multi[x+1][temp];
here when temp goes beyond 5 it will give you exception as you have multi[][]=new int [con][6];
change the line int temp = rand.nextInt(5);
also you have another issue multi[x+1], when you have x=99 that time it will try to make 100 which is causing the issue, remember array index starts with 0
Problem
I have written a loop in which I fill an array with Sum objects. Everything works fine, but as soon as the loop gets to the next iteration it overwrites the first index of the array.
What have I tried
I tried to see if maybe my problem resides in a different piece of code (such as my Sum class). But could not find anything that would disturb the loop.
I tried to find other variables with the same name (even in other methods, since I was desperate) and see if I maybe changed my iterator somewhere else. I couldn't find anything related to that.
I tried looking around on the internet and SO to find something related to accidentally overwriting arrays but couldn't find anything either.
Code
public Task(Object[] parameters)
{
this.number_of_sums = Integer.parseInt((String)parameters[0]);
this.variables_per_sum = Integer.parseInt((String)parameters[1]);
this.sum_parameters = new Object[this.variables_per_sum];
this.sums = new Sum[this.number_of_sums];
int z = 0;
for(int i = 0; i < this.number_of_sums; i++)
{
int x = 0;
for(int j = (2 + z); j < ((this.variables_per_sum + 2) + z); j++)
{
this.sum_parameters[x] = parameters[j];
x++;
}
this.sums[i] = new Sum(this.sum_parameters);
System.out.println("Index 0: "+sums[0]); //1st iteration: 1 + 1 //2nd iteration: 2 - 1
System.out.println("Index 1: "+sums[1]); //1st iteration: null //2nd iteration: 2 - 1
z += this.variables_per_sum;
}
}
Expectations
I'm expecting the output of 1 + 1 and 2 - 1. I am however getting the following: 2 - 1 and 2 - 1 when I'm done.
If anyone spots anything I'm doing wrong or would like to see more information or code on my side please say so. Thanks in advance.
I'm going to assume the Sum class doesn't store its sum, but instead computes it from the array it was constructed with whenever it's needed.
It looks like all the Sum objects will share the same array -- you're passing the same reference every time you construct a Sum. Furthermore, every time you loop over j you overwrite the contents of that array.
So when everything is done, all the sums are the same.
You should be able to get around this by giving each Sum a different sum_parameters:
public Task(Object[] parameters)
{
this.number_of_sums = Integer.parseInt((String)parameters[0]);
this.variables_per_sum = Integer.parseInt((String)parameters[1]);
this.sums = new Sum[this.number_of_sums];
int z = 0;
for(int i = 0; i < this.number_of_sums; i++)
{
Object[] sum_parameters = new Object[this.variables_per_sum];
int x = 0;
for(int j = (2 + z); j < ((this.variables_per_sum + 2) + z); j++)
{
sum_parameters[x] = parameters[j];
x++;
}
this.sums[i] = new Sum(sum_parameters);
System.out.println("Index 0: "+sums[0]); //1st iteration: 1 + 1 //2nd iteration: 2 - 1
System.out.println("Index 1: "+sums[1]); //1st iteration: null //2nd iteration: 2 - 1
z += this.variables_per_sum;
}
}
Each one of your Sum objects is constructed with this.sum_parameters as a parameter:
this.sums[i] = new Sum(this.sum_parameters);
When sum_parameters is modified in each iteration of the outer loop, it changes internally in the objects constructed around references to it.
You should make an internal copy of sum_parameters in each Sum object.