I have an issue with string array where's the program takes the use names the put it in the screen. I did some coding and creating 2D games and android app but the fact I never used array for saving scores or something and now I'm stuck and need to learn it and code below think of it as we are putting degrees for collage students put the error that the array is making an error and I can't figure it out why the full code below:
public static void main(String[] args) {
// TODO Auto-generated method stub
Chatlength = new String[10];
for(i =0; i <= Chatlength.length ; i++){
Scanner s = new Scanner(System.in);
String ss = s.nextLine();
Chatlength[i] = ss;
}
while(true){
if(i > Chatlength.length){
int ints = 0;
while(ints <10){
System.out.println("Name "+ints+": "+Chatlength[ints]);
ints++;
}
}
}
It gives me and error with Chatlength[i] = ss;.
I'm guessing you're getting an ArrayIndexOutOfBoundsException due to your loop bounds:
for(i =0; i <= Chatlength.length ; i++){
That should be:
for (int i = 0; i < Chatlength.length; i++) {
... using a local variable declaration instead of the static variable which I assume you've declared in code that you haven't shown us.
An array of length 10 has valid indexes of 0 to 9 inclusive. It's very rare that you actually want <= for a loop index variable when you're trying to iterate over a collection. (All the standard collections in Java are 0-based, so you pretty much always want to have an exclusive upper bound.)
Additionally, I strongly suggest that you start following Java naming conventions.
The condition is culprit. You are going one plus the size of array.
i <= Chatlength.length
Change it to
i < Chatlength.length
Check your for - loop:
for(i =0; i <= Chatlength.length ; i++)
should be
for(i =0; i < Chatlength.length ; i++)
you didn't declare the array first:
Chatlength = new String[10]; //Wrong code;
change it to :
String[] Chatlength = new String[10];
then java is zero based and you should use this:
for(i =0; i < Chatlength.length ; i++)
There is no such index i=10 for the array you created, as per your condition in loop, it allows i=10 (i<= Chatlength.length) which is not a valid array location hence you got the exception
Related
I'm new to Java programming, but after looking around on this site, I'm fairly certain this should work.
public static int[] ArrayStringToArrayInt(String[] arrayString) {
int[] arrayInt = new int[arrayString.length]; //Array of Ints for output
for (int i = 0; i <= arrayString.length; i++ ) { //Run through the
arrayInt[i] = Integer.parseInt(arrayString[i]); //array, Parsing each
} //item into an int
return arrayInt;
}
What I want this method to do is take an input array: ["1","2","3"] with each item being a string
and return [1,2,3] where each item is an int.
I'm calling the method with this code
int[] toBeSorted = ArrayStringToArrayInt(inputStringArray);
In this case, toBeSorted is both being declared here and initialized at the same time.
Whenever I try to run this I get the following error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at sorter.Sorter.ArrayStringToArrayInt(Sorter.java:31)
at sorter.Sorter.main(Sorter.java:22)
Java Result: 1
Line 31 is the body of my For loop, the part that does the parsing, and line 22 is the place where the method is called.
The reason I need this is because I'm trying to take an input from the user, with the Scanner class and want them to be able to enter many numbers at the same time. I then use a delimiter pattern to turn the input into an array. While that seems fine, I could only figure out how to make the input be an array of strings, not ints, which is my problem.
So I guess what I'm asking is
1) why does my code not work?
and
2) is there an easier way to take an input from the user and turn it into an array of ints than this?
For those who would like to see my entire code, here it is
The bit in the middle with the test variable and the adding of two numbers is just a way for me to test my code and see if it worked. It should show the result of adding the first two numbers in the list that you entered
package sorter;
import java.util.Scanner;
import java.util.Arrays;
public class Sorter {
public static void main(String[] args) {
Scanner userInput = new Scanner( System.in );
System.out.println("Enter a list to be sorted, seperate numbers by commas:");
String input = userInput.nextLine(); //Gets aan input as a String
String delims = "[,]+"; //Use Comma as Delimiter
String[] inputStringArray = input.split(delims); //Parse String and creates
//an array
System.out.println(Arrays.toString(inputStringArray)); //Outputs a string of
//the given array
int[] toBeSorted = ArrayStringToArrayInt(inputStringArray);
int test = toBeSorted[0] + toBeSorted[1];
System.out.println(test);
}
public static int[] ArrayStringToArrayInt(String[] arrayString) {
int[] arrayInt = new int[arrayString.length]; //Array of Ints for output
for (int i = 0; i <= arrayString.length; i++ ) { //Run through the
arrayInt[i] = Integer.parseInt(arrayString[i]); //array, Parsing each
} //item into an int
return arrayInt;
}
}
You got the range of the loop wrong :
for (int i = 0; i <= arrayString.length; i++ )
should be
for (int i = 0; i < arrayString.length; i++ )
The valid indices of the array are between 0 and arrayString.length - 1.
As a bonus, here's a nicer way to achieve the same with Java 8:
public static int[] ArrayStringToArrayInt(String[] arrayString)
{
return Stream.of(arrayString).mapToInt(Integer::parseInt).toArray();
}
Off-by-one error here:
for (int i = 0; i <= arrayString.length; i++ ) {
^
It should be:
for (int i = 0; i < arrayString.length; i++ ) {
This is wrong
for (int i = 0; i <= arrayString.length; i++ )
should be
for (int i = 0; i < arrayString.length; i++ )
The indexes of the array are between the 0 and length -1
Variable i should go from 0 to N-1, N being the length of the array. Java arrays, like C ones are zero-based, which means that you should iterate them from 0 to N-1. So your for should look like this:
for (int i = 0; i < arrayString.length; i++)
You could use a stream:
Arrays.stream(arrayString).mapToInt(Integer::parseInt).toArray()
Simply change this statement
for (int i = 0; i <= arrayString.length; i++ )
To
for (int i = 0; i < arrayString.length; i++ )
It will work fine. ArrayIndexOutOfBoundsException means you're trying to access an index in the array that does not exist.
For example,
int [] a= new int [5];
Then the indices available to me are
a [0], a [1], a [2], a [3], and a [4]
I cannot access
a [5]
And if i try i would get ArrayIndexOutOfBoundsException.
That means array indices start at 0 and go upto array length-1.
Hope this helps.
I've tried several times but to no avail it's only outputting the first row. It's a 2D array, and it's supposed to output 4 rows. It's not showing any errors. I think the logical error may be from the for loops which contain the output statements.
package aitiDay5;
public class WorldCup {
public static void main(String[] args){
int i=0,j=0;
String [][] countries = new String [6][];
countries[0]=new String[4];
countries[1]=new String[4];
countries[2]=new String[4];
countries[3]=new String[4];
countries[4]=new String[4];
countries[5]=new String[4];
countries[6]=new String[4];
countries[0][0]="Countries ";
countries[0][1]="Rival ";
countries[0][2]="Grade ";
countries[0][3]="Points ";
countries[1][0]="Ghana";
countries[1][1]="Germany";
countries[1][2]="C";
countries[1][3]="3";
countries[2][0]="Croatia";
countries[2][1]="Greece";
countries[2][2]="B+";
countries[2][3]="A-";
countries[3][0]="USA";
countries[3][1]="Portugal";
countries[3][2]="B+";
countries[3][3]="4";
countries[4][0]="Spain";
countries[4][1]="Costa Rica";
countries[4][2]="F+";
countries[4][3]="-2";
countries[5][0]="Brazil";
countries[5][1]="Germany";
countries[5][2]="Z";
countries[5][3]="-32";
countries[6][0]="Argentina";
countries[6][1]="Holland";
countries[6][2]="A";
countries[6][3]="10";
for ( i=0;i<=countries.length;i++){
System.out.println("\n");
for(j=0;j<countries.length;j++){
System.out.println(countries[i][j]+ " ");
}
}
}
}
Your first for loop statement should just use the < operator, not the <= operator.
Your second loop should index into the row to check the length.
for (i = 0; i < countries.length; i++){
System.out.println("\n");
for(j = 0; j < countries[i].length; j++){
System.out.println(countries[i][j] + " ");
}
}
Also, since it appears you want 7 rows, you need to change
String [][] countries = new String [6][];
to
String [][] countries = new String [7][];
Side Note: you don't have to have i and j outside of the for loops. You can do this:
for(int i = 0; ......){ ... }
YOu need to change this line
for(j=0;j<countries.length;j++){
System.out.println(countries[i][j]+ " ");
To this:
for(j=0;j<countries[i].length;j++){
System.out.println(countries[i][j]+ " ");
Otherwise it will just loop on the single array twice
The problem is simple and you are correct, there is a logical error in your nested for loop.
You are running it against the length of the entire array it should be changed to:
for(j=0;j<countries[i].length;j++){
System.out.println(countries[i][j]+ " ");
}
Your inner for loop statement should be for(j = 0; j < countries[i].length; j++), and your outer for loop should be for(i = 0; i < countries.length; i++).
As it stands you're not fully looping through the second dimension. I'm actually very surprised that you're not seeing an error, because based on your arrays you should have a ton of illegal access exceptions. Java gets really upset when you try to access past the end of an array (example: your inner arrays only contain 4 elements, but your inner for loop iterates until j=5, meaning you're accessing the 5th element in a 4-element array)
String[] month = {"Jan","Feb","Mar","Apr","May","June","July","Aug","Sept","Oct","Nov","Dec"};
int[] monthArray = new int[12];
String[][] itemArray = new String[12][10];
Variables
monthArray[i] = input.nextInt();
itemArray[monthArray[i]-1][e] = input.next();
Store a maximum of 5 String values on user input's month.
for(int i=0;i<e;e++){
System.out.println(itemArray[monthArray[i]-1][i]);
}
Having a problem displaying the String values (it just keep repeating the first String value) under user input's month.
You are increasing e instead of i in the last loop. e is the limit and not the variable you use for the iteration and thus the loop will not terminate until you overflow int.
for(int i = 0; i < e; i++ /* Note the usage of i here*/) {
use i++ instead of e++
here e stands for the limit
and i stands for the variable.
Since you have a 2D array, maybe you want something more like this, to print out the values, once, the array has been populated.
String[][] itemArray = new String[12][10];
for(int i = 0; i < itemAreray.length; i++){
for (int j = 0; j < itemArray[i].legnth; j++){
System.out.println(itemArray[i][j]);
}
}
Unless you're having difficulty populating the array. Then that's a different problem
I'm pretty much a noob to programming but i have researched all over the place and cant find an answer. im using eclipse and every time i run my program it says:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at computer.guess(game1player2.java:24)
at game1player2.main(game1player2.java:39)
Here's my code:
import java.util.Scanner;
class computer{
int g = 0;
int[] compguess = new int[g];
void guess(){
int rand;
while(0 < 1){
int i;
rand = (int) Math.ceil(Math.random()*10);
for (i = 1; i < compguess.length; i++){
if(rand == compguess[i]){
break;
}
}
if(i > compguess.length){
g++;
rand = compguess[g];
System.out.println(compguess[compguess.length]);
}
}
}
}
public class game1player2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
computer computer1 = new computer();
for(int a = 0; a < 2; a++){
computer1.guess();
for(int n = 0; n <= computer1.compguess.length; n++)
System.out.println(computer1.compguess[n]);
}
{
input.close();
}
}
}
i am now really confused, i am trying to make a computer generate a random number 1-10, but if it is already in the array generates another one.
int g = 0;
int[] compguess = new int[g];
Your array is size 0, so you have no valid entries.
Since you initialized g as zero, your array compguess has a length of zero. Next when you enter your for loop you assign 1 to i which will allow you to enter into the if condition at the end of guess which will try to access element compguess[1] but this cannot exist because the array is of size zero.
You will run into problems if you do not correct the following.
Change: for(int n = 0; n <= computer1.compguess.length; n++)
To: for(int n = 0; n < computer1.compguess.length; n++)
If your array length is 8 then the last item in the array will be index 7, but the <= tells the loop to grab item index 8.
Your compguess has a length of 0, and you are starting your for loop with i = 1, wich is already greater than 0.
compguess is a zero-length array. If you try to index it, you will fall out of the array and hence the ArrayIndexOutOfBoundsException
If your intent is to make the array longer and add a new item to the end of it, you can't do that. I'm guessing that this is what you were trying to do here:
rand = compguess[g];
First of all, if the language did allow it, you'd want to write it the other way:
compguess[g] = rand;
because you're trying to put a value into a new element of the array, not read from the array. This would actually work in some languages (JavaScript, Perl, others). In Java, however, when you create an array object with something like new int[], the size is fixed. You can't make it longer or shorter.
You probably want to use an ArrayList, which does let you create an array that you can make longer. See this tutorial.
This question already has answers here:
C++ - Using 'i' to check different variables in a for loop
(3 answers)
Closed 10 years ago.
So you can do it the very simple but long way as below
System.out.println(myArray[1]); //This = 1.56
System.out.println(myArray[2]); //This = 1.72
But how would you do it using a for loop to retrieve the values and print them? So it could look something like
for (int i = myArray[]; j < myArray.length; i++) {
System.out.println(i);
}
So the for loop will then go through the array and println all the values stored at its positions e.g [1] = 1.56, [2] = 1.72. How could you get the for loop to do this? Thanks
Just print myArray[i] in the loop:
for (int i = 0; i < myArray.length; ++i) {
System.out.println(myArray[i]);
}
I also had to fix your loop variable.
Another way is to use a "for each" loop:
for (double val : myArray) {
System.out.println(val);
}
Just changing a couple of things in your code gives you your answer:
for (int i = 0; i < myArray.length; i++) {
System.out.println(myArray[i]);
}
This sets i = 0 initially, looping as long as i is less than the length of your array, and incrementing i with one each iteration. This will make i step from 0 ... (myArray.length - 1), and print all the values.
int[] myArray ={1,3,2};
for (int i : myArray) {
System.out.println(i);
}
You mean something like this using for-each loop?
Use Formatter to print in the way you want, and a simple for to get the values from array.
for (int i = 0; i < myArray.length; i++) {
System.out.format("[%d] = %.2f\n", i, myArray[i]);
}
For an array like {1.567, 1.444, ...} it will print
[0] = 1.57
[1] = 1.44
You can modify the format to what you desire.