When I try running the code below I get
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 7
at java.lang.String.charAt(String.java:658)
at main.main(main.java:27)
Java Result: 1
I still have to add in something that gets the highest value and the lowest. The program has to work through a string. The method I used below, is not from any where else, I just kinda did it that way, but the teacher hinted at using loops. Any suggestions? I think It might be because the garbage in the array.
int highValue,lowestValue,sum;
int random;
int check, otherCheck;
int a = 0,b = 0,c = 0,d = 0,e = 0;
String passingRandomIn;
//Create a object that generates a random number 4-8
Random ran = new Random();
//Generates a random number between 4 and 8
random = ran.nextInt(5)+4;
//Sets the randomly generated number equal to check and other check
check = random;
otherCheck = random;
//Declare an array of 5 characters[0-4] inclusive
char[] myCharArray = new char[4];
//To string
passingRandomIn = Integer.toString(random);
//Pass in the random numbers(character per character from the string)
switch(check){
case 8: myCharArray[4] = passingRandomIn.charAt(4);
check--;
case 7: myCharArray[3] = passingRandomIn.charAt(3);
check--;
case 6: myCharArray[2] = passingRandomIn.charAt(2);
check--;
case 5: myCharArray[1] = passingRandomIn.charAt(1);
check--;
case 4: myCharArray[0] = passingRandomIn.charAt(0);
break;
}
//Add the array of characters to an array of integers
switch(otherCheck)
{
case 8: a = Character.getNumericValue(myCharArray[4]);
case 7: b = Character.getNumericValue(myCharArray[3]);
case 6: c = Character.getNumericValue(myCharArray[2]);
case 5: d = Character.getNumericValue(myCharArray[1]);
case 4: e = Character.getNumericValue(myCharArray[0]);
break;
}
sum = a + b + c + d + e;
System.out.println(sum);
}
}