簡體   English   中英

用於掃描儀驗證的多個條件 while 循環

[英]Multiple conditions while loop for scanner validation

大家好,試圖驗證 java 中用戶輸入的 integer 范圍。 我是編程和 java 的新手。 我遇到困難的部分是倍數和接近尾聲。 我不確定如何處理它,所以已經猜到了。 我無法在其他地方找到合適的解決方案;

    import java.util.Scanner;


  class Main {
  public static void main(String[] args) {
   
   // Create a Scanner 
   Scanner sc = new Scanner(System.in);
    int number;
     do {
    System.out.println("Please enter window width");
    while (!sc.hasNextInt()) {
        System.out.println("That's not a number!");
        sc.next(); // this is important!
    }
    number = sc.nextInt();
     } while ((width > 0.5 & <2.5) && (height >0.5 & <3.5));  
   System.out.println("Window is:" + height + "m high " + width + "m wide.");
    }

您的 do while 循環語法似乎不正確,請嘗試以下代碼:

do {
System.out.println("Please enter window width");
while (!sc.hasNextInt()) {
    System.out.println("That's not a number!");
    sc.next(); // this is important!
}
number = sc.nextInt();
 } 
while((width > 0.5 && width < 2.5) && (height > 0.5 && height < 3.5));

使用Double#parseDouble解析輸入,如果它不成功(即如果拋出異常),則回送以要求用戶重試。 驗證輸入(是否為數字)后,根據您的要求驗證范圍。

執行以下操作:

import java.util.Scanner;

class Main {
    static Scanner sc = new Scanner(System.in);

    public static void main(String[] args) {

        // Variables for width and height
        double width, height;

        // Input width
        do {
            width = getDimennsion("Please enter window width between 0.5 & 2.5: ");
        } while (width < 0.5 || width > 2.5);// Loop back in case of invalid dimension

        // Input height
        do {
            height = getDimennsion("Please enter window height between 0.5 & 3.5: ");
        } while (height < 0.5 || height > 3.5);// Loop back in case of invalid dimension

        System.out.println("Width: " + width + ", Height: " + height);
        // ...Rest of the processing
    }

    static double getDimennsion(String msg) {
        boolean valid;
        double num = 0;
        do {
            valid = true;
            System.out.print(msg);
            try {
                // Get input
                num = Double.parseDouble(sc.nextLine());
            } catch (IllegalArgumentException e) {
                System.out.println("Invalid input. Please try again");
                valid = false;
            }
        } while (!valid);// Loop back in case of invalid input
        return num;
    }
}

示例運行:

Please enter window width between 0.5 & 2.5: a
Invalid input. Please try again
Please enter window width between 0.5 & 2.5: 10
Please enter window width between 0.5 & 2.5: 2
Please enter window height between 0.5 & 3.5: b
Invalid input. Please try again
Please enter window height between 0.5 & 3.5: 15
Please enter window height between 0.5 & 3.5: 3
Width: 2.0, Height: 3.0

暫無
暫無

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

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