簡體   English   中英

Java為什么掃描儀無法在交換機內工作

[英]Java why wont scanner work inside a switch

我有一台掃描儀,詢問一些偏好。 它在0到3之間創建一個int變量choice 。然后執行以下操作:

String location;
switch(choice){
    case 0:
        System.out.println("Please type the zip codes you would like to search in a comma separated list");
        location = input.nextLine();
        break;
    case 1:
        System.out.println("Please type the street names you would like to search in a comma separated list");
        location = input.nextLine().toUpperCase();
        break;
    case 2:
        System.out.println("Please type the boroughs you would like to search in a comma separated list");
        location = input.nextLine().toUpperCase();
        break;
    default:
        location = "none";
        break;
    }
String locations[] = location.split("\\s*,\\s*");

現在對我來說這似乎很好,但是當選擇設置為0,1或2時,它將打印正確的行,但是跳過用戶必須輸入內容的部分(看起來像location = ...的行)

這意味着它不會給用戶提供輸入任何內容的機會,因此locations成為空白列表。 為什么會發生這種情況,我該如何解決?

您可能正在最后輸入之后閱讀換行符,而不是真正的下一行。 嘗試:

int choice = input.nextInt();

input.nextLine(); // <--- Eat it here!
String location;
switch(choice){
    case 0:
        Syst...

您提示選擇的nextInt()調用不會結束該行。 因此,在nextInt() nextLine()之后對nextLine()的第一次調用將返回一個空String。 要解決此問題,請在整數之后吃掉空行,然后繼續前進。

我和你一樣面臨着同樣的問題。 嘗試:

case 'f' :
                System.out.println("Enter a word or phrase to be found:");
                scnr.nextLine();
                String phrase = scnr.nextLine(); //

在讀取之前將nextLine放在開關之前。

System.out.print("Digite um número ente 1 e 9: ");
int opc = read.nextInt();
read.nextLine();
switch(opc) {

並使用nextLine()讀取您的值

case 6:
    String[] procurados = read.nextLine().split(" ");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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