简体   繁体   English

如何在此循环中合并“仅int”输入?

[英]How can i make incorporate a 'int only' input in this loop?

I've been messing around with this code for about an hour now trying to make it loop if the user inputs a character instead of a number 我一直在弄乱这段代码大约一个小时,试图在用户输入字符而不是数字时使其循环播放

    System.out.println("Enter level student last completed (0-3): "); 
    int level = in.nextInt();
    while (level > 3 || level < 0){
        System.out.println("Please enter a valid level!: ");
        level = in.nextInt();
    }

I thought of adding !in.hasNextInt() to the line while (level > 3 || level < 0) to make it 我想到了将!in.hasNextInt()添加到while (level > 3 || level < 0)

while (!in.hasNextInt() || level > 3 || level < 0)

but this doesn't help as the programme still crashes if a character is input. 但这无济于事,因为如果输入了字符,程序仍然会崩溃。

edit: 编辑:

    System.out.println("Enter level student last completed (0-3): "); 
    int level = 1; //in.nextInt();
    while (in.hasNextInt()==false || level > 3 || level < 0){
        in.next();
        System.out.println("Please enter a valid level!: ");
    }
    level = in.nextInt();

You can create a while loop to repeatedly ask for an input until it gets the kind it likes 您可以创建一个while循环来重复请求输入,直到获得喜欢的输入为止

Basic solution 基本解决方案

    int i;
    while(scan.hasNextInt()==false){ //keep asking until it gets something it likes
        scan.next(); //<--consume bad input, important!
        System.out.println("Only integers are valid");
    }
    i=scan.nextInt();

    System.out.println(i);

Advanced solution 先进的解决方案

You can package this up into method which will make life easier when we want to incorporate more logic 您可以将其打包为方法,当我们希望合并更多逻辑时,这将使工作更轻松

public static int getSafeInteger(){
    Scanner scan=new Scanner(System.in); //if using scanner over and over consider passing the scanner as an argument
    while(scan.hasNextInt()==false){
        scan.next();
        System.out.println("Only integers are valid");
    }
    return scan.nextInt();
}

Then we can use that method within your existing loop 然后我们可以在您现有的循环中使用该方法

    System.out.println("Enter level");

    Scanner scan=new Scanner(System.in);

    int level=getSafeInteger();
    while (level > 3 || level < 0){
        System.out.println("Please enter a valid level!: ");
        level = getSafeInteger();
    }

使用nextLine()并尝试使用Integer.parseInt(String)其解析为整数。

You could do something like this: 您可以执行以下操作:

int level;
while (true) {
    if (in.hasNextInt()) {
        // now we know at least the input is a number
        if (level > 3 || level < 0) {
            // aww, it's an invalid number :(
            in.nextLine(); // clear bad input
            System.out.println("Please enter a valid level (0-3)!: ");
        } else {
            // hooray! store the input now
            level = in.nextInt();
            break; // out of the infinite loop
        }
    } else {
        // input is not a number
        in.nextLine(); // clear bad input
        System.out.println("Please enter a number!: ");
    }
}

Try this: 尝试这个:

Scanner sc = new Scanner(System.in);
int level;

System.out.printf("Enter level student last completed (0-3): "); 
while(true) {
    try {
        level = Integer.parseInt(sc.next());
        if (level < 4 && level > -1) {
            break;
        }
    } catch (Exception ex) { }
    System.out.printf("Please enter a valid level!: ");
}

you can set default value of level more than 3 and do following 您可以将级别的默认值设置为大于3并执行以下操作

            do
            {
                System.out.println("Enter level student last completed (0-3): ");
                try{
                 level = in.nextInt();
                }catch(InputMismatchException e){
                    System.out.println("Not a valid Number");
                    in.nextLine();
                }
            }while (level > 3 || level < 0);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我怎样才能使这段代码更简单? 另外我如何检查输入是否为int? - How can i make this code simpler? Also how can i check if input is an int? 如何根据用户输入创建一个持续运行的循环 - How can I make a loop that keeps going based on user input 如何使用户仅输入小数? - How can I make users ONLY input decimal? 如何将平方根 function 合并到我正在尝试制作的计算器中? - How can I incorporate a square root function into this calculator I am trying to make? 如何将浮点数四舍五入到小数点后两位,合并当前月份和年份,并修复我的循环? - How can I round my float to two decimal places, incorporate the current month and year, and fix my loop? 如何将条件合并到尝试捕获中? - How can I incorporate a condition into a try catch? 如何使用用户输入在 java 中创建一个循环,并使变量成为最后一个输入和上一个输入? - How can I make a loop in java with user input and have variables that are the last input and previous input? 如何让用户输入一个int值并将它们拆分为单个数字并放入数组? - How can I make user to input an int value and split them up to single number and put in array? 如何将String转换为int? - How can I make convert a String to int? 在 java 中,我如何制作一个循环语句来打印从 1 到分配给来自扫描仪输入的 int 的值的正数总和? - In java, how do I make a loop statement to print the sum of positive nums from 1 to the value assigned to an int from an input from a scanner?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM