String Arrays not working. Compiler not interacting - 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]);
}

Related

2D array filling | ArrayIndexOutOfBoundsException error

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.

Why is it allowed to declare a variable in a for loop?

I'm a student currently learning java at school (Beginner) and I was wondering about something.
I have a basic knowledge of coding from other languages and I don't understand a particular thing in Java.
If I were to declare a variable (let's use an int as a example) inside a loop wouldn't that mean that I'm declaring the same variable over and over?
This is what I mean:
for (int i = 0; i < 3; i ++) {
int x = 5;
}
Isn't it the same thing as this? (This one is incorrect)
int x = 5;
int x = 5;
If not, Why? Both of them are / declare the same variable twice, though I know that in loops the variable is local and can't be used outside of the loop (I don't think thats the issue though).
I also know that you can't declare the same variable twice so I don't understand how the first example is legal.
Thanks so much :D
This Question has be solved, Thanks to everyone that helped :D
for (int i = 0; i < 3; i ++) {
int x = 5;
}
is actually equivalent to:
{
int x = 5;
}
{
int x = 5;
}
{
int x = 5;
}
Each x variable is declared in a separate scope.
scope is in one iteration, after end of loop, scope doesn't exist.
simple example:
for (int i = 0; i < 4; i++) {
int x = 0;
System.out.println(x);
x++;
}
output:
0
0
0
0
Lets take 1st expression
for (int i = 0; i < 3; i ++) {
int x = 5;
}
Here scope of variable x is within the loop block
So each time a new loop starts scope is already released.
So there is no error
If you change the same code to like this
for (int i = 0; i < 3; i ++) {
int x = 5;
int x = 5;
}
Now there will be an error as x is already in scope and you are again trying to define.
This is allowed
for (int i = 0; i < 3; i ++) {
int x = 5;
x = 5;
}
as you are resigning the variable
the variable x has life time that begin at when you declare it and ends at the closing block for the for-loop.
in other word x is born when you enter new iteration and dies when iteration ends (or dies at the end of block that contains it)
In each iteration of your loop, a variable x of type int is "created" and assigned the value 5. As soon as the iteration finishes, this variable is "destroyed" and by the next iteration the cycle starts again.
So there are never 2 variables by the same name in the same scope.
It is generally good practice to make the variable avayable to the smallest context possible: if you only need it inside the loop declaring it inside it is considered good practice.
For the loop declaration case, your value gets reassigned basically.
This might proove interesting to read and add further informations on the matter: Declaring variables inside or outside of a loop
This is also a legal thing to do
for (int i= 0; i < 1000000000; i++) {
int j = i & i+1 ;
}
These are legal because at the end of the loop the declared variable "ceases to exists" in order to be reformed the next execution
Well, when you declare int x = 5; inside the loop, you're declaring it in a local scope (which starts from its { to }) so the variable x will be destroyed when it gets out of its scope which means for the next loop iteration, it's a new x so that's why you can do that and since it's destroyed when it gets out of scope it can't be used/seen outside the scope.
Just to clarify the concept of allowing variable declaration in a loop, I've declared the same variable again in the loop, and got error "A local variable or function named 'x' is already defined in this scope"(I wrote this code in C#, but you should get similar message in Java):
If I declare the variable in a different scope outside the loop, there will be no error as the scope is different:
for (int i = 0; i < 3; i++)
{
int x = 5;
}
{
int x = 5;
}
If we couldn't declare variables in loop, we had to write the following code:
{
int x = 5;
// Do something with x=5
}
{
int x = 5;
// Do something with x=5
}
{
int x = 5;
// Do something with x=5
}
But with loop, we can just write the following instead of writing 3 scopes:
for (int i = 0; i < 3; i++)
{
int x = 5;
// Do something three times with x=5
}

Counting the amount of a specific object in 2D Array Java

In a checkers game for my CS class I have run into trouble with counting how many of a specific color piece are on the board.
Here is the getter method:
public int getCheckersBlue()
{
int counter = 0;
for(int x = 0; x <= 8; x++)
{
for(int y = 0; y <= 12; y++)
{
if(c[x][y].equals(Color.BLUE))
{
counter++;
}
}
}
return counter;
}
The constructor for c:
private CheckersBoard[][] c = new CheckersBoard[8][8];
Whenever trying to run the game in Greenfoot a null pointer exception is thrown even when the code compiles. Even with everything declared, everything has something it's pointing to. Any suggestions?
I see two major problems in your code:
You're iterating over 0-8 elements for x and 0-12 for y, but in declaration you has 0-7 for x and the same for y
NullPointerException. This caused because array declaration will fill your array with null values, so you're comparing null with Color.Blue which is incorrect.
With the both fixes code will look like this
public int getCheckersBlue()
{
int counter = 0;
for(int x = 0; x < 8; x++)
{
for(int y = 0; y < 8; y++)
{
if(Color.BLUE.equals(c[x][y]))
{
counter++;
}
}
}
return counter;
}
But I think it's still logically incorrect.
Okay, a few of things...
You are iterating through 12 every time in the inner loop when it should be 8.
Color.Blue is a JavaFX Paint, I believe. This is not really what you should be using. Unless you have made your own Enumeration type of Color, you should do so. Here is a link for how to do so with relevant examples.
You are checking equality of two different types: CheckersBoard and Color. You should have a CheckersBoard.getSpace(x, y).getColor() or CheckersBoard.getSpace(x, y).getOccupancy() (which should have a NoOccupancy option) if we want to be completely logistically sound with our naming.

How to change values of an array inside a class

I have a question about my code.
class Zillion
{
private int[] d;
public Zillion(int size)
{
d = new int[size];
}
public void timesTen()
{
for(int i = 0; i<d.length;i++)
{
d[i] = d[i + 1];
}
d[d.length]=0;
}
public String toString()
{
String num;
num= "";
for(int i = 0; i<d.length; i++)
{
num = num + d[i];
}
return num;
}
}
Here in my class Zillion, I am trying to multiply a number that is represent by an array by 10. So what I did was I move the elements at each index to the left and change the value at the last index to 0. For instance,
0 1 4 8 will be come 1 4 8 0.
I am not sure whether my logic will work but that was my first start.
First, I am trying to change the values at each index of the array with an assigned size and here is my driver file.
class Driver
{
public static void main(String[] args)
{
Zillion z = new Zillion(5);
System.out.println(z); // 00000
for (int j = 0; j <= 5; j += 1)
{
z[j]=j;
}
System.out.println(z);
}
}
However, Java throws me an error and says: "Error:(32, 14) java: array required, but Zillion found".
I took C++ and I believe I could change array values like z[j] = j but I guess it is different in Java.
Is there a way I can change the values of the specific index I want? The reason why I used the for loop is because I could not think of any method that I can use to assign the values at each index I want. Is that possible that in the Driver file I create an array, say, 0148 and call my "timesTen" method to give me what I want?
Thank you!
You need to expose the array d of zillion class using a gettor method.
public getArray(){ return d;}
Instead of z[j]=j; you need to use z.getArray()[j] = j
Also your timesTen method will cause arrayindex out of bounds exception in the line
d[d.length]=0;
Java array is not dynamically growing so, Index should be lesser than array size.
You can't index a class, only arrays.
Define a method in Zillion
class Zillion {
public void set(int index, int value) {
// TODO implement
}
}
In your loop, call z.set(j, j)
Note: j <= 5 will cause an out of bound exception
I believe I could change array values like z[j] = j
You could - if z would be an array! But, as the error message also states, it is an object of type Zillion:
Zillion z = new Zillion(5);
You are using instance z of Zillion class, use array instead of it.
//Create getter method in Zillion Class
public int[] getD() {
return d;
}
//And access that array in Driver Class
int[] array = z.getD();
for (int j = 0; j < 5; j += 1) {
array[j] = j;
}
Moreover, you are going to face an
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
because of the statement d[d.length] = 0; in your timesTen() implementation. You have to replace that line with:
d[d.length-1] = 0;
This is not an answer to your question, because you have already received valuable ones, but I hope it could help you.

How to get data form an array in a method

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);
}

Categories