[英]Method in Java program won't pick up the user 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被完全忽略了。 谁能解释我在做什么错?
这是因为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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.