Java 如何防止字符串在while循环中重复打印?
我现在正在做老师给我的一些练习。这些是度假用的,所以我不能在那里寻求帮助 我有一段代码,它从用户定义的一个整数创建一个乘法表,从用户定义的最小值到最大值 在将扫描器中的任何变量设置为下一个整数之前,我会检查扫描器是否有一个整数。这工作正常,但我不希望它打印出错误消息十亿次 有什么窍门或其他特殊的方法来解决这个问题吗Java 如何防止字符串在while循环中重复打印?,java,string,while-loop,println,Java,String,While Loop,Println,我现在正在做老师给我的一些练习。这些是度假用的,所以我不能在那里寻求帮助 我有一段代码,它从用户定义的一个整数创建一个乘法表,从用户定义的最小值到最大值 在将扫描器中的任何变量设置为下一个整数之前,我会检查扫描器是否有一个整数。这工作正常,但我不希望它打印出错误消息十亿次 有什么窍门或其他特殊的方法来解决这个问题吗 public class MultiplicationTable { private int intervalMin; private int intervalMax
public class MultiplicationTable
{
private int intervalMin;
private int intervalMax;
private int multiplier;
private int result;
private Scanner sc;
public MultiplicationTable()
{
multiplier = 0;
intervalMin = 0;
sc = new Scanner(System.in);
while (multiplier == 0)
{
System.out.println("Please enter the integer you wish to show the table for");
if (sc.hasNextInt())
{
multiplier = sc.nextInt();
}
else
{
System.out.println("Input is not an integer\n");
}
}
while (intervalMin == 0)
{
System.out.println("\nPlease enter the integer defining the start of the table");
if (sc.hasNextInt())
{
intervalMin = sc.nextInt();
}
else
{
System.out.println("Input is 0 or not an integer\n");
}
}
while (intervalMax == 0)
{
System.out.println("\nPlease enter the integer defining the end of the table");
if (sc.hasNextInt())
{
int i = sc.nextInt();
if (i > intervalMin)
{
intervalMax = i;
}
else
{
System.out.println("\nEnd integer must be greater than start integer");
}
}
else
{
System.out.println("Input is 0 or not an integer");
}
}
System.out.println("\nTable for integer " + multiplier + " from " + intervalMin + " to " + intervalMax + "\n");
for (int i = intervalMin; i <= intervalMax; i++)
{
result = i * multiplier;
System.out.println(i + " * " + multiplier + " = " + result);
}
}
}
请尝试此操作,只需将所有代码包装在try catch中:
try {
while (intervalMax == 0) {
System . out . println("\nPlease enter the integer defining the end of the table");
if (sc . hasNextInt()) {
int i = sc . nextInt();
if (i > intervalMin) {
intervalMax = i;
} else {
throw new Exception("\nEnd integer must be greater than start integer");
}
}
}
} catch (Exception e) {
System . out . println(e . getMessage());
}
您没有使用用户输入到扫描仪缓冲区中的内容,这就是为什么sc.hasNextInt会在不等待下一个用户输入的情况下继续执行。 解决方案是在if条件之后添加sc.nextLine。 例如:
boolean gotInteger = false;
while (!gotInteger) {
System.out.println("Please enter the integer you wish to show the table for");
if (sc.hasNextInt()) {
multiplier = sc.nextInt();
gotInteger = true;
} else {
System.out.println("Input is not an integer\n");
}
sc.nextLine();
}
是的,这确实结束了印刷业。但关键是它必须返回while循环的顶部,直到它实际得到一个整数。sc.nextLine将使用最后一个用户输入,并且当再次调用sc.hasNextInt时,它将等待另一个用户输入。它肯定会工作。谢谢!然而,我不能说我完全理解它。