java - 无法实现检测输入是否为整数的系统
问题描述
我正在尝试创建一个系统,询问用户他们希望一个短语重复多少次,然后它检查答案是整数还是字符串。当我不尝试实现这个系统并让它只询问短语以及应该重复多少次时,该程序运行良好,但当我尝试检查次数是否为整数时,它会变得很糟糕。
import java.util.*;
public class Phrase {
public static Scanner phraseScan = new Scanner (System.in);
public static Scanner amountScan = new Scanner (System.in);
public static void main (String[] args ) {
System.out.println("What phrase do you want repeated?");
String phrase = phraseScan.nextLine();
int phraseLoops = 0;
System.out.println("How many " + phrase + "s" + " do you want?");
int desiredPhraseLoops = amountScan.nextInt();
for (;;) {
if (!amountScan.hasNextInt()) {
System.out.println("Integers only please");
amountScan.next();
}
desiredPhraseLoops = amountScan.nextInt();
if (desiredPhraseLoops >= 0) {
System.out.println("Valid amount!");
continue;
} else {
break;
}
}
System.out.println(desiredPhraseLoops + " " + phrase + "s coming your way!");
do {
System.out.println(phrase);
phraseLoops++;
} while (phraseLoops != desiredPhraseLoops);
System.out.println("You printed " + phraseLoops + " " + phrase + "s" );
}
}
我试过的:
try {
desiredPhraseLoops = amountScan.nextInt();
} catch (InputMismatchException exception) {
System.out.println("This is not an integer.");
}
if (!amountScan.hasNextInt()) {
System.out.println("Good.");
} else {
System.out.println("Enter an Integer please.");
}
每当我尝试任何事情时,它都会询问我想要哪个短语以及我想要重复多少次。然后程序就停止了,无论我输入一个整数还是一个字符串,它都没有给我任何其他提示。
输出是这样的:
你想重复哪个短语?测试 你想要多少测试?3
就是这样。
解决方案
首先,只需使用一个 Scanner 对象。您不需要更多的键盘输入。
如果你愿意,你可以坚持使用Scanner#nextLine()方法,例如:
Scanner userInput = new Scanner(System.in);
String phrase = "";
while (phrase.equals("")) {
System.out.println("What phrase do you want repeated?");
phrase = userInput.nextLine();
// VALIDATION:
// Was anything other than a empty string (spaces)
// or longer than 2 characters supplied?
if (phrase.trim().equals("") || phrase.length() < 3) {
// Nope!
System.err.println("Invalid Input!. Enter a proper phrase!");
phrase = "";
}
// Yes, allow the prompt loop to exit.
}
String phraseLoopsNumber = "";
while (phraseLoopsNumber.equals("")) {
System.out.println("How many " + phrase + "s" + " do you want?");
phraseLoopsNumber = userInput.nextLine();
// VALIDATION:
// Did the User supply a string representation of an integer value?
if (!phraseLoopsNumber.matches("\\d+")) {
// Nope!
System.out.println("Invalid Input (" + phraseLoopsNumber + ")! An integer value is expected!");
phraseLoopsNumber = "";
}
// Yes he/she/it did...Allow prompt loop to exit.
}
int numberOfLoops = Integer.parseInt(phraseLoopsNumber);
// Do what you have to do with the desired number of loops contained
// within the numberOfLoops integer variable.
在上面的代码中,String#matches()方法与一个小的正则表达式(RegEx) 一起使用。"\\d"
传递给matches()方法的表达式检查它所处理的字符串是否包含所有(1 个或多个)数字。
但是,如果您一心想要使用Scanner#nextInt()方法,那么您可以这样做:
int numberOfLoops = -1;
while (numberOfLoops == -1) {
System.out.println("How many " + phrase + "'s" + " do you want?");
// Trap any input errors against the Scanner.nextInt() method...
// This would be a form of validation.
try {
numberOfLoops = userInput.nextInt();
// Consume the newline from ENTER key in case a nextLine() prompt is next.
userInput.nextLine();
} catch (Exception ex) {
System.out.println("Invalid Input! An integer value is expected!");
// Consume the newline from ENTER key in case a nextLine() prompt is next.
// The first one above would of been skipped past if nextInt() threw an exception.
userInput.nextLine();
numberOfLoops = -1;
continue; // continue loop so as to re-prompt
}
// Further Validation:
// Did the User supply a number greater than 0?
if (numberOfLoops < 1 ) {
// Nope!
System.out.println("Invalid Input (" + numberOfLoops + ")! A value 1 or greater is expected!");
numberOfLoops = -1;
}
// Yes he/she did...Allow prompt loop to exit.
}
// Do what you have to do with the desired number of loops contained
// within the numberOfLoops integer variable.
推荐阅读
- php - 使用 laravel 在 XAMPP 中的服务器上找不到请求的 URL
- google-cloud-dataflow - Apache Beam ReadFromText() 模式匹配不返回结果
- android - Kotlin 中是否可以接受“MyType+MyProtocol.kt”扩展文件名?
- python - 使用 beautifulsoup 在 pandas 数据框中抓取问题/错误
- javascript - 尝试映射数组时出错。TypeError:无法读取未定义的属性“地图”
- cmake - CMake: ''配置过程出错,项目文件可能无效" ; OpenPose
- python - Lua脚本不会执行python脚本
- cmake - 使用 CMAKE 自定义 Visual Studio 解决方案平台名称
- python - 附加到列表仅附加第一项
- octave - 如何在 Octave 中加载用户指定的文件