用户输入仅检查int [英] user input check int only

查看:88
本文介绍了用户输入仅检查int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过限制用户可以输入的内容(例如:

I am trying to have my user input not crash my program by restricting what the user can input such as:

  1. 仅是一个整数
  2. 介于1到30之间

我编写的代码仅在一定程度上有效.如果您输入的内容不是整数,它将对其进行检查并要求您再次输入.如果您继续输入除int以外的任何内容,则再次输入.我还有另一个while循环,如果它确实输入一个int,并且它在1-30区域之外,那么它将要求用户再次输入.但是,此后,如果用户键入另一个除int外的任何东西",程序将崩溃.我尝试将 sc.hasnextint()和输入检查在1-30个条件之间结合起来,但是如果我将 sc.nextint()放在 sc.hasnextint()并且用户输入除int之外的任何内容,程序崩溃.如果将其放在条件循环之后,则不会声明用户输入.

The code that I've written works only up to a certain point. If you enter something thats not an int it will check it and ask you to enter again. Then again if you keep typing anything but an int. I have another while loop if it does type an int, and if it's outside the 1-30 zone then it will ask the user to input again. However after that if the user types another "anything but an int" the program will crash. I've tried to combine both the sc.hasnextint() and the check for input between 1-30 condition but if i put the sc.nextint() before the sc.hasnextint() and the user enters anything but an int, the program crashes. If I put it after the condtion loop, then the userinput will not be declared.

int choose;
System.out.print("type an integer: ");
Scanner sc=new Scanner(System.in);

while (!sc.hasNextInt() ) { 
    System.out.println("only integers!: "); 
    sc.next(); // discard 
} 

choose=sc.nextInt();

while (choose<=0 || choose>30)
{
    System.out.print("no, 1-30: ");
    choose=sc.nextInt();
}
sc.close();

推荐答案

您需要组合两个循环,以便每次最终用户输入新内容时都进行两次检查:

You need to combine the two loops, so that both checks happen every time the end-user enters something new:

for(;;) {
    if(!sc.hasNextInt() ) { 
        System.out.println("only integers!: "); 
        sc.next(); // discard
        continue;
    } 
    choose=sc.nextInt();
    if( choose<=0 || choose>30)
    {
        System.out.print("no, 1-30: ");
        continue;
    }
    break;
}

退出循环后, choose 是介于 1 30 之间的数字.

After the loop exits, choose is a number between 1 and 30, inclusive.

这篇关于用户输入仅检查int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆