簡體   English   中英

Java程序中的方法不會接收用戶輸入

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM