mardi 8 décembre 2020

Java if-else substring.equals throws exception [closed]

I'm unsure why, but it throws an exception when "answer" begins with a zero. The program is basically supposed to simulate a lottery. The computer generates a three digit number, 000-999, and asks the user to enter a number. If two sequential numbers match the generated numbers, the user wins.

java.lang.StringIndexOutOfBoundsException: begin 1, end 3, length 2

Full code:

import java.util.Scanner;
public class Lottery
{
    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        int counter;
        String b = "";
          for (counter = 0; counter < 3; counter++){
          double randInt = Math.random();
          double i = randInt * 10;
          int a = ((int)i);
          b = b + Integer.toString(a);
        }
        System.out.println(b);
        System.out.print("Enter in a number to see if you won the lottery. ");
        int answerInt = in.nextInt();
        String answer = Integer.toString(answerInt);
        if (answer.substring(0,2).equals (b.substring(0,2)) || answer.substring(1,3).equals (b.substring(1,3)) || answer.equals (b.substring(0,3))){
            System.out.println("You Won!");
        } else {
            System.out.println("Sorry, you didn't win.");
            
        }
        System.out.println(b.substring(0,2));
            System.out.println(b.substring(1,3));
            System.out.println(b.substring(0,3));
    } 
    
}

Aucun commentaire:

Enregistrer un commentaire