【问题标题】:How can I validate data from scanner (Java) [duplicate]如何验证来自扫描仪(Java)的数据 [重复]
【发布时间】:2017-10-11 09:51:41
【问题描述】:

我需要让用户输入一个从 1 到 10 的数字,然后得到这个数字的阶乘,除了验证用户名(在范围内 && 不是字符串)之外,我什么都能做

p>
package test2;

import java.util.Scanner;

public class Test2 {

    public static void main(String[] args) {

        int userInput = 0 ;
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter a number from 2 to 100");

        if (sc.nextInt() < 101) {
            userInput = sc.nextInt();
        }
        System.out.println(userInput);

    }

}

【问题讨论】:

  • 你不要求用户名,所以我猜你谈到了用户输入。基本上,您想要求用户输入一些输入,直到找到有效的输入?
  • 你说的是什么用户名?从 1 到 10(或根据您的代码 2 到 100)的数字应该是用户名吗?
  • 您的问题描述性不够。你说你可以做除了验证用户名之外的所有事情。您需要向用户询问的用户名在哪里?它是变量 userInput 吗?

标签: java validation java.util.scanner


【解决方案1】:

您可以尝试的一种方法是

public static void main(String[] args) {

int userInput = 0 ;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a number from 2 to 100");

while (!sc.hasNextInt())
{
 System.out.println("wrong input");
 sc.next();
}  

if (sc.nextInt() < 101) {
    userInput = sc.nextInt();
}
System.out.println(userInput);

 }
}

【讨论】:

    【解决方案2】:
        int userInput = 0;
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter a number from 2 to 100");
        while (!sc.hasNextInt()) {
            System.out.println("Please enter number");
            sc.next();
        }
        while(true) {
            userInput = sc.nextInt();
            if (userInput > 2 && userInput < 100) {
                break;
            }else{
                System.out.println("Please enter a number between 2 to 100");
            }
        }
        System.out.println(userInput);
    

    【讨论】:

    • 如果用户输入"yohoho"会怎样?
    • 这不检查输入类型。
    • 我已经更新了我的答案,现在检查一下
    【解决方案3】:

    或者干脆使用do-while

     do {
    
       userInput = sc.nextInt();
    
     } while (userInput < 1 || userInput > 10);
    

    【讨论】:

      猜你喜欢
      • 2018-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-06
      • 2015-10-02
      相关资源
      最近更新 更多