【发布时间】:2021-10-21 14:53:35
【问题描述】:
我试图提示用户输入 5 个整数,但它不会循环多次。我不知道为什么会发生这种情况,并且我自己无法解决错误
代码:
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner s= new Scanner(System.in);
int counter= 0;
Boolean inputOK;
int iInput;
int data[]= new int[5];
// while (counter<5);
do {
System.out.println(" Please enter an integer");
while (!s.hasNextInt()) {
System.out.println("Invalid input");
System.out.println("Please Enter an integer value");
s.next();}
iInput=s.nextInt();
if (iInput < -10 || iInput > 10) {
System.out.println("Not a valid integer. Please enter a integer between -10 and 10");
inputOK = false;
} else {
inputOK = true;
}
System.out.println("before while loop"+ inputOK);
} while (!inputOK);
counter++;
System.out.println("counter value is"+ counter);
}
}
【问题讨论】:
-
你有一个计数器,但你没有使用它的循环。看起来你开始写一个,然后把它注释掉了。
-
注意这个任务不需要使用
do while循环,你可以使用简单的while loop。如果您的inputOK为假,此while (!inputOK);也会导致您的代码卡住并无限循环。最后,您只输入一个 int,因此循环只会运行一次while (!s.hasNextInt())... -
嗨,凯文,欢迎来到 SO。我建议养成使用适当缩进的习惯。它不仅对于编写功能代码至关重要,而且还是与他人就您的代码进行交流的基础(例如在 SO 上,但在您的职业生涯后期,当许多其他人将阅读您的代码时)
标签: java while-loop do-while