Java程序中的方法不会获取用户输入

时间:2014-11-26 21:23:24

标签: java string input

所以我在这里有一些代码:

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();
    }
}

我在这里得到输出:

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

在我看来,(String)b完全被忽略了。谁能解释我做错了什么?

1 个答案:

答案 0 :(得分:0)

那是因为scanner.nextInt()不消耗用户输入的输入的新行字符。您应该在kb.nextLine()之后拨打scanner.nextInt(),以便使用留下的新线字符。

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();

或替换kb.nextInt();

的所有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();