作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
你好!我正在尝试进行一些数据输入验证,但一直无法弄清楚。当我尝试验证输入的第一个字符是否为字母时,出现无限循环。 . . .
感谢您的帮助!
public class methods
{
public static void main(String args[]) throws IOException
{
String input ="";
int qoh=0;
boolean error=true;
Scanner keyboard = new Scanner (System.in);
//while (error)
//{
//error=true;
while (error==true)
{
System.out.print("\nEnter Quantity on Hand: ");
input = keyboard.nextLine();
if (input.length() <1)
{
System.out.println("\n**ERROR06** - Quantity on hand must be between 0 and 500");
error=true;
System.out.println(qoh);
System.out.println(input);
}
else
{
error=false;
}
}
error = true;
while (error==true)
{
if (Character.isLetter(input.charAt(0)))
{
System.out.println("\n**ERROR06** - Quantity on hand must be between 0 and 500");
error=true;
System.out.println(qoh);
System.out.println(input);
}
else
{
qoh = Integer.parseInt(input);
error=false;
}
}
}
}
最佳答案
您的第二个 while 循环中没有 input = keyboard.nextLine();
。
您可以重构您的代码,使其仅在出现错误时请求新的输入。所以就在“错误...”的系统输出之后
额外:我实际上会做不同的事情。开头的 'error = true' 有点令人困惑,因为可能没有错误。
例如,您可以编写一个名为 tryProcessLine 的方法,该方法读取输入并在正常时返回 true,在出现错误时返回 false,而不仅仅是执行类似 while(!tryProcessLine()){ } 的操作
下面的工作示例:
import java.io.IOException;
import java.util.Scanner;
public class Methods {
private static int qoh;
public static void main(String args[]) throws IOException {
while (!tryProcessLine()) {
System.out.println("error... Trying again");
}
System.out.println("succeeded! Result: " + qoh);
}
public static boolean tryProcessLine() {
String input = "";
Scanner keyboard = new Scanner(System.in);
System.out.print("\nEnter Quantity on Hand: ");
input = keyboard.nextLine();
try {
qoh = Integer.valueOf(input);
if (qoh < 0 || qoh > 500) {
System.out.println("\n**ERROR06** - Quantity on hand must be between 0 and 500");
return false;
} else {
return true;
}
} catch (NumberFormatException e) {
System.out.println("\n**ERROR06** - Quantity on hand must be numeric");
return false;
}
}
}
关于java - Java 中的无限 While 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2342633/
我是一名优秀的程序员,十分优秀!