簡體   English   中英

掃描儀在if語句中無法正常工作

[英]scanner not working properly inside if statement

該代碼提示用戶通過輸入Y或N(是/否)來確認預訂。 如果他們鍵入y或Y,它將調用setBooked()方法,該方法基本上只是將boolean變量“ booked”設置為“ true”。 isBooked()僅返回該boolean值,因此我可以測試before / after來查看它是否真正起作用。

實際的代碼確實沒有按我預期的那樣工作,如果您鍵入“ y”,它將立即正常工作,但是如果您鍵入其他任何內容,它將再次提示您,如果您鍵入“ y”,它將再次工作,但是這次您鍵入任何內容否則它將停止並轉到下一個“客戶”(此方法被調用了大約8次)

因此,從根本上來說,是否有一個原因提示用戶兩次,而不是僅僅評估他們第一次鍵入“ y”或“ Y”的內容?

System.out.println(customer.isBooked());
System.out.println( "Confirm booking for " + customer.getName() + "(Y/N)");
Scanner scan = new Scanner(System.in);

if (scan.nextLine().equals("y") || scan.nextLine().equals("Y"))
    customer.setBooked();

System.out.println("Booked");
System.out.println(customer.isBooked());

您應該使用#equalsIgnoreCase

使用scan.nextLine().equalsIgnoreCase("y")作為|| 將去檢查兩個條件,因為系統將提示您兩次輸入nextLine()

如果您希望用戶繼續輸入,如果用戶輸入了錯誤的輸入,則應使用循環並提示直到條件得到滿足。

例如

     do {
         System.out.println("Type 'y' OR 'Y' to Exit!");
         if(s.nextLine().equalsIgnoreCase("y")) {
            customer.setBooked();
            break;
         }
      } while(true);

它提示兩次 ,因為您它提示兩次

此處: if (scan.nextLine().equals("y") || scan.nextLine().equals("Y"))您兩次調用scan.nextLine()

將您的代碼更改為:

String s = scan.nextLine();
s=s.toLowerCase(); // change "Y" to "y" . Cleaner code.

if(s.equals("y")){
//your code here
}

嘗試使用以下代碼:

System.out.println(customer.isBooked());
System.out.println( "Confirm booking for " + customer.getName() + "(Y/N)");
Scanner scan = new Scanner(System.in);
boolean flag = scan.nextLine().equalsIgnoreCase("y");
if (flag)
    customer.setBooked();
System.out.println("Booked");
System.out.println(customer.isBooked());

您使用OR在條件中兩次調用scan.nextLine() 這意味着如果左側不正確,那么它將繼續向右側。 但是,如果為true,則OR為true,無需評估右側。 這就是為什么如果他們在第一次輸入y時只要求一次,否則要求兩次。

如果只希望它要求一次,則不scan.nextLine()的值分配給變量,然后在if語句中使用該變量。

String result = scan.nextLine();
if (result.equals("y") || result.equals("Y")) {
    ...
}

是的,您打了兩次電話

 scan.nextLine().equals("y") || scan.nextLine().equals("Y") //2 scan.nextLine()

將您的代碼更改為

 String line=scan.nextLine();
 if ("y".equals(line) ||"Y".equals(line)) // avoid NullPointerException too

或使用equalsIgnoreCase()

 if("y".equalsIgnoreCase(scan.nextLine())) // avoid NullPointerException too 

您正在說它應該在這里提示兩次:

if (scan.nextLine().equals("y") || scan.nextLine().equals("Y"))

通過兩次調用scan.nextLine()

您可以執行以下操作:

...
String next = scan.nextLine();    

if (next.equals("y") || next.equals("Y"))
...

暫無
暫無

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

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