简体   繁体   English

Java程序中的方法不会接收用户输入

[英]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. 在我看来,(String)b被完全忽略了。 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. 这是因为scanner.nextInt()不使用用户键入的输入的换行符。 You should call kb.nextLine() after the scanner.nextInt() just to consume the new line character left behind. 你应该叫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();

Or replace all your kb.nextInt(); 或替换所有的kb.nextInt(); for Integer.parseInt(kb.nextLine()); 对于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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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