【发布时间】:2020-05-31 05:17:53
【问题描述】:
我正在尝试创建一个系统,询问用户他们希望一个短语重复多少次,然后它会检查答案是整数还是字符串。当我不尝试实现这个系统并且只询问短语以及应该重复多少次时,该程序运行良好,但是当我尝试检查次数是否为整数时,它会变得很糟糕。
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
就是这样。
【问题讨论】: