繁体   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