my code is throwing an error "String index out of bound : 1" , here is the code :
package inlamningsuppgift2;
import java.util.Random;
import java.util.Scanner;
import java.lang.Math;
public class inlamningsuppgift2del2 {
public static void main(String[] args) {
System.out.println("Guess a number between 01-99");
randomNumber();
}
public static void randomNumber () {
Scanner scanner = new Scanner(System.in);
Random random = new Random();
int value = Integer.valueOf(scanner.nextLine());
String str1 = Integer.toString(value);
String sa = String.format("%02d", value);
int randomNum = 10 * random.nextInt(9);
int randomNum2 = 1 * random.nextInt(9) +1;
int wholeNum = randomNum + randomNum2;
String str2 = Integer.toString(randomNum + randomNum2);
String s = String.format("%02d", randomNum + randomNum2);
System.out.println("You guessed :" + sa);
System.out.println("The correct number is : " + s);
if (str2.charAt(0) == str1.charAt(0) && str2.charAt(1) == str1.charAt(1)) {
System.out.println("Congratulations, you guessed the right number in the right order and won 1000$!");
}
else if (str1.charAt(0) == str2.charAt(1) && str1.charAt(1) == str2.charAt(0) ) {
System.out.println("Congratulations, you guessed the right number but in the wrong order and won 500$ !");
}
else if (str2.charAt(0) == str1.charAt(0) && str2.charAt(1) != str1.charAt(1)
|| str2.charAt(0) != str1.charAt(0) && str2.charAt(1) == str1.charAt(1)
|| str1.charAt(1) == str2.charAt(0) && str1.charAt(0) != str2.charAt(1)
|| str1.charAt(0) == str2.charAt(1) && str1.charAt(1) != str2.charAt(0)) {
System.out.println("Congratulations, you guessed one of the numbers right!");
}
else {
System.out.println("Sorry you guessed wrong, try again");
}
}
}
The assignment instructions are : "A lottery program generates a double digit number between 01-99. If the user guesses the number right in the right order, they win 1000$. If the user guesses the right number in the wrong order, example 16 instead of 61, they win 500$. If the user guesses one of the numbers right, they win 100$."
The code is working fine when user input and/or randomNum are 10 and above. However ,when it is below 10 , the error occurs because the value is read as 1 char instead of 2, example : 09 is read as 9 , so charAt(1) does not exist.
How can I fix this? Is there a way to make 0 count as charAt(0) so that charAt(1) counts the digits after the 0, or do I need to change something else?
Thanks!
==for primitiveintor theequalsmethod forInteger. Converting your numbers to Strings and then those Strings to chars and comparing those chars is needlessly complicated and will introduce problems you are currently experiencing.String sa = String.format("%02d", value);but you usestr1in the main code. Usesainstead which will have 2 chars even if the number is less than 10.