首页 > 解决方案 > I have to enter my input twice to get the output

问题描述

When it comes to the letter a,b,c , if i enter them i need to enter them twice(2 spaces is used). Compared to when I enter an integer or an blank space, my Exception returns it with 1 line. I tried using only String answer = scan.next but it does not read and return when i enter empty spaces so i'm using String answer = scan.nextLine();

public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);

    String questions[] = {"What is the color of the sky? ", "What is 1 + 1? ",
            "What is the capital of the Philippines? ", "Who is the current president of the Philippines? ",
            "What is the capital of Japan? ", "What is 2 + 3? ",
            "What is 9 + 1?", "What is the capital of the United States? ",
            "What is 10 + 10? ", "How many hand fingers do humans have? "};

    String choices[] = {"a","b","c"};

    int x = 0;
    int y = 0;
    
     System.out.println("Choose a Letter: a , b , c");

    try {

        while(x<=9) {
           
            System.out.println("No." + (x+1) + " " + questions[x]);
            String answer = scan.nextLine();
            x++;
            
            if(answer.equals(choices[0])) {
                scan.nextLine();

            } else if (answer.equals(choices[1])) {
                scan.nextLine();

            } else if (answer.equals(choices[2])) {
                scan.nextLine();

            } else if (answer.equals(" ")) {
                throw new EmptyInputException();

            } else {
                throw new InvalidLetterException();
            }   
    
        } 

    } catch(InvalidLetterException e) {
        System.out.println(); //Spacing
        System.out.println(e.getMessage());
        System.out.println(); //Spacing
        System.out.println("You can try again.");
        System.out.println(); //Spacing
        do {
            System.out.println("No." + (y+1) + " " + questions[y]);
            scan.next();
            y++;
            
        }while(y<=9);
        
    } catch (EmptyInputException e) {
        System.out.println(); //Spacing
        System.out.println(e.getMessage());
        System.out.println(); //Spacing
        System.out.println("You can try again.");
        System.out.println(); //Spacing
        do {
            System.out.println("No." + (y+1) + " " + questions[y]);
            scan.next();
            y++;
        }while(y<=9);
        
    }
}

标签: java

解决方案


推荐阅读