簡體   English   中英

使用Scanner進行兩次檢入while循環-Java

[英]Two checks in while loop with Scanner - java

我試圖用while循環做兩次檢查:

1)如果用戶輸入的不是int,則顯示“錯誤”

2)一旦用戶輸入一個int ,如果它是一位數字,則顯示“僅兩位數字”並保持循環直到輸入兩位數字int(因此也應使用IF)

目前,我只完成了第一部分:

    Scanner scan = new Scanner(System.in);

    System.out.println("Enter a number");

    while (!scan.hasNextInt()) {

        System.out.println("error");
        scan.next();

    }

然而,如果可能的話,我想有一個 while循環兩張支票。

那就是我被困住的地方...

由於您已經有兩個答案。 這似乎是一種更清潔的方法。

Scanner scan = new Scanner(System.in);

String number = null;
do {
    //this if statement will only run after the first run.
    //no real need for this if statement though.
    if (number != null) {
        System.out.println("Must be 2 digits");
    }

    System.out.print("Enter a 2 digit number: ");
    number = scan.nextLine();

    //to allow for "00", "01". 
} while (!number.matches("[0-9]{2}")); 
System.out.println("You entered " + number);

首先將輸入作為字符串。 如果可以轉換為Int,則進行檢查,否則說2位數字是可以接受的。 如果不可轉換為數字,則會引發錯誤。 所有這些都可以在while循環中完成。 然后,您會收到“是否要繼續?”的提示,並檢查答案是否為“是” /“否”。 相應地從while循環中斷。

如上所述,您應該始終將輸入作為字符串輸入,然后嘗試將其解析為int

package stackManca;

import java.util.Scanner;

public class KarmaKing {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String input = null;
        int inputNumber = 0;
        while (scan.hasNextLine()) {
            input = scan.next();
            try {
                inputNumber = Integer.parseInt(input);
            } catch (Exception e) {
                System.out.println("Please enter a number");
                continue;
            }
            if (input.length() != 2) {
                System.out.println("Please Enter a 2 digit number");
            } else {
                System.out.println("You entered: " + input);
            }
        }
    }
}

要將其作為一個循環,它比兩個循環要混亂一些

int i = 0;
while(true)
{
    if(!scan.hasNextInt())
    {
        System.out.println("error");
        scan.next();
        continue;
    }
    i = scan.nextInt();
    if(i < 10 || >= 100)
    {
        System.out.println("two digits only");
        continue;
    }
    break;
}
//do stuff with your two digit number, i

與兩個循環

int i = 0;
boolean firstRun = true;
while(i < 10 || i >= 100)
{
    if(firstRun)
        firstRun = false;
    else
        System.out.println("two digits only");

    while(!scan.hasNextInt())
    {
        System.out.println("error");
        scan.next();
    }

    i = scan.nextInt();
}
//do stuff with your two digit number, i

暫無
暫無

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

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