使用Scanner时,确保用户输入是一个整数

时间:2017-02-09 05:48:53

标签: java java.util.scanner

期望的结果:

  • 接受用户输入
  • 确保用户一次只输入1个整数值
  • 在变量
  • 中存储该整数

我尝试通过执行以下操作来实现此目的:

  • 将用户输入存储在变量
  • 计算变量
  • 中的令牌数量
  • 如果没有一个令牌,请拒绝输入
  • 如果输入不是数据类型int,请拒绝输入

代码:

    Scanner scan = new Scanner(System.in);

    System.out.println("Enter an integer:");
    String myString = scan.nextLine();
    int tokens = new StringTokenizer(myString, " ").countTokens();

    while (tokens != 1 && !scan.hasNextInt()) {
        System.out.println("Enter a single integer");
        myString = scanner.nextLine();
        tokens = new StringTokenizer(myString, " ").countTokens();
    }

    int number = scanner.nextInt();
    System.out.println(number);

这段代码充满了漏洞。输出不一致且不合需要。它通常以抛出java.util.InputMismatchException错误结束,表示它尝试存储的值不是int。我经历过这个错误发生在一个循环之后和多个循环之后,即使输入的类型和数量相同(例如2个字符串)。

我应该继续使用此代码,还是应该尝试从另一个角度解决此问题?

1 个答案:

答案 0 :(得分:2)

我已经修改了你的程序了一下。我的方法是接受一行输入。如果输入包含多个令牌,请要求用户重新输入输入。如果只有一个输入,检查输入是否为整数,如果不是,则作为再次提供输入的用户。

似乎对我有用:

StringTokenizer
  

更新:不使用 Scanner scanner = new Scanner(System.in); String myString; boolean validInput; int number; do { System.out.println("Enter a single integer"); myString = scanner.nextLine(); try { number = Integer.parseInt(myString); validInput = true; } catch(NumberFormatException e) { validInput = false; number = -1; } }while (validInput == false); scanner.close(); System.out.println(number);

的替代方法
Scanner
  

更新2 :在接受输入之前使用正则表达式验证输入的另一种方法。

Scanner scanner = new Scanner(System.in); System.out.println("Enter a single integer"); String integerPattern = "[+-]?\\d+$"; // positive or negative and digits only while(scanner.hasNext(integerPattern) == false) { String x = scanner.nextLine();// capture and discard input. System.out.println("Enter a single integer. '" + x + "' is an invalid input."); } int number = scanner.nextInt(); // capture input only if it matches pattern. scanner.close(); System.out.println("number: " + number); 允许我们使用正则表达式来匹配输入。如果输入与模式匹配,则可以使用它来接受输入。否则,丢弃它并要求用户再次提供输入。

以下是代码:

con = file("pathtotargetfile", "r")
readsizeof<-2    # read size for one step to caculate number of lines in file
nooflines<-0     # number of lines
while((linesread<-length(readLines(con,readsizeof)))>0)    # calculate number of lines. Also a better solution for big file
  nooflines<-nooflines+linesread

con = file("pathtotargetfile", "r")    # open file again to variable con, since the cursor have went to the end of the file after caculating number of lines
typelist = list(0,'c',0,'c',0,0,'c',0)    # a list to specific the lines data type, which means the first line has same type with 0 (e.g. numeric)and second line has same type with 'c' (e.g. character). This meet my demand.
for(i in 1:nooflines) {
  tmp <- scan(file=con, nlines=1, what=typelist[[i]], quiet=TRUE)
  print(is.vector(tmp))
  print(tmp)
}
close(con)

希望这有帮助!

相关问题