简体   繁体   中英

Method in Java program won't pick up the user input

So I have some code here:

import java.util.*;

public class tester 
{
    public static void main(String args[])
    {
        Scanner kb = new Scanner(System.in);
        String b;
        System.out.println("Choose a number 1-10.");
        int a = kb.nextInt();
        a = a * 2;
        a = a + 5;
        a = a * 50;
        System.out.println("Enter the year you were born in.");
        int c = kb.nextInt();
        System.out.println("Did you already have your birthday this year?");
        b = kb.nextLine();
        if (b.equals("yes"))
        {
            a = a + 1764;
        }
        else
        {
            a = a + 1763;
        }
        a = a - c;
        System.out.println(a);
        kb.close();
    }
}

I get the output here:

Choose a number 1-10.
5
Enter the year you were born in.
2014
Did you already have your birthday this year?
499

It seems to me as if the (String) b is completely ignored. Can anyone explain what I am doing wrong?

That's because the scanner.nextInt() does not consume the new line character of the input typed by the user. You should call kb.nextLine() after the scanner.nextInt() just to consume the new line character left behind.

int c = kb.nextInt();
System.out.println("Did you already have your birthday this year?");
kb.nextLine(); //consumes new line character left by the last scanner.nextInt() call
b = kb.nextLine();

Or replace all your kb.nextInt(); for Integer.parseInt(kb.nextLine());

Scanner kb = new Scanner(System.in);
String b;
System.out.println("Choose a number 1-10.");
int a = 0;
try {
    a = Integer.parseInt(kb.nextLine());
} catch (NumberFormatException numberFormatException) {
    a=0;
}
a = a * 2;
a = a + 5;
a = a * 50;
System.out.println("Enter the year you were born in.");
int c = 0;
try {
    c = Integer.parseInt(kb.nextLine()); //consumes the new line character
} catch (NumberFormatException numberFormatException) {
    c=0;
}
System.out.println("Did you already have your birthday this year?");
b = kb.nextLine();
if (b.equals("yes")) {
    a = a + 1764;
} else {
    a = a + 1763;
}
a = a - c;
System.out.println(a);
kb.close();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM