期望的结果:
我尝试通过执行以下操作来实现此目的:
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个字符串)。
我应该继续使用此代码,还是应该尝试从另一个角度解决此问题?
答案 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)
希望这有帮助!