Java While循环不会停止异常循环
可能遗漏了一些非常愚蠢的东西,但是我的while循环不会停止打印错误消息 有人能快速看一下并给我指出正确的方向吗Java While循环不会停止异常循环,java,exception,while-loop,Java,Exception,While Loop,可能遗漏了一些非常愚蠢的东西,但是我的while循环不会停止打印错误消息 有人能快速看一下并给我指出正确的方向吗 package week5; import java.util.*; public class Week5 { public static void main(String[] args) { Scanner myKeyboard = new Scanner(System.in); inputInt();
package week5;
import java.util.*;
public class Week5 {
public static void main(String[] args) {
Scanner myKeyboard = new Scanner(System.in);
inputInt();
}
public static int inputInt(){
Scanner myKeyboard = new Scanner(System.in);
System.out.println("Enter number:");
int num;
boolean carryOn = true;
while (carryOn = true) {
{
try {
num = myKeyboard.nextInt();
carryOn = false;
}
catch (Exception e) {
System.out.println ("Integers only");
}
}
}
return 0;
}
这条线就是问题所在
while (carryOn = true) {
您使用的不是比较运算符=
,而是赋值运算符=
。因此,本质上,每次迭代都将carryOn
设置为true
,然后自动运行循环体,因为条件基本上变为
while (true) {
把问题线改成
while (carryOn == true) {
这条线就是问题所在
while (carryOn = true) {
您使用的不是比较运算符=
,而是赋值运算符=
。因此,本质上,每次迭代都将carryOn
设置为true
,然后自动运行循环体,因为条件基本上变为
while (true) {
把问题线改成
while (carryOn == true) {
就你而言:
while(carryOn==true)
或
将在您的情况下解决您的问题:
while(carryOn==true)
或
将解决您的问题除了无限循环和您总是
返回0这一事实之外代码>无论用户类型如何,代码都比需要的复杂得多
// only create one scanner
private static final Scanner myKeyboard = new Scanner(System.in);
public static void main(String[] args) {
int num = inputInt();
// do something with num
}
public static int inputInt() {
System.out.println("Enter number:");
while (true) {
if (myKeyboard.hasNextInt()) {
int num = myKeyboard.nextInt();
myKeyboard.nextLine(); // discard the rest of the line.
return num;
}
System.out.println ("Integers only, please try again");
}
}
除了无限循环和您总是返回0的事实之外代码>无论用户类型如何,代码都比需要的复杂得多
// only create one scanner
private static final Scanner myKeyboard = new Scanner(System.in);
public static void main(String[] args) {
int num = inputInt();
// do something with num
}
public static int inputInt() {
System.out.println("Enter number:");
while (true) {
if (myKeyboard.hasNextInt()) {
int num = myKeyboard.nextInt();
myKeyboard.nextLine(); // discard the rest of the line.
return num;
}
System.out.println ("Integers only, please try again");
}
}
谢谢你的回答,虽然我已经尝试了两种解决方案,但只要我输入了除整数以外的任何内容,则只打印整数错误,直到我结束程序。谢谢你的回答,虽然我尝试了两种解决方案,但只要我输入除整数以外的任何内容,则只打印整数错误,直到我结束程序。这可能是最常见的错误软件开发中的常见错误。谢谢你回忆过去;)尝试在cachmyKeyboard.next()中添加return-1;在解决它的过程中,欢呼声可能是软件开发中最常见的错误。谢谢你回忆过去;)尝试在cachmyKeyboard.next()中添加return-1;在比赛中,干杯,伙计们