gpt4 book ai didi

java - Java 中的无限 While 循环

转载 作者:行者123 更新时间:2023-11-30 06:38:20 24 4
gpt4 key购买 nike

你好!我正在尝试进行一些数据输入验证,但一直无法弄清楚。当我尝试验证输入的第一个字符是否为字母时,出现无限循环。 . . .

感谢您的帮助!

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com