gpt4 book ai didi

java - 程序循环而不运行完整代码

转载 作者:行者123 更新时间:2023-12-01 18:53:24 25 4
gpt4 key购买 nike

我正在为一个项目编写一个异常类,并且被一个问题难住了。该类要求提供一个包含银行账户的文件名,读取该文件,并检查它们是否符合特定条件。如果它们不满足这些条件之一,则会抛出 BankAccountException 类型的错误,这是一个自定义错误类,它只是扩展 Exception 类并进行重命名。我遇到的问题是,一旦我输入文件名,程序就会立即询问另一个文件的名称。我已经坐了一段时间了,无法弄清楚,任何帮助将不胜感激。

   import java.util.*;


import java.io.*;

public class BankAccountProcessor{


public static void main(String[] args){
boolean runProgram = true;
Scanner input = new Scanner(System.in);
String filename;

while (runProgram = true){
try{
System.out.println("Please enter the name of the file you want to parse.");
filename = input.next();
File file = new File(filename);
Scanner inputFile = new Scanner(file);
while (inputFile.hasNext()){
String accountLine = inputFile.nextLine();
if (BankAccountProcessor.isValid(accountLine) == true){
System.out.println("Line " + accountLine + " has been processed.");
}
runProgram = false;
}
}
catch(FileNotFoundException e){
System.out.println("That file does not exist");
}
catch(BankAccountException e){

}
}
}

private static boolean isValid(String accountLine) throws BankAccountException{
StringTokenizer stringToken = new StringTokenizer(accountLine, ";");
String tokenOne = stringToken.nextToken();
String tokenTwo = stringToken.nextToken();
if (stringToken.countTokens() != 2){
throw new BankAccountException("Invalid Bank Account Info");
}
else if (tokenOne.length() != 10){
throw new BankAccountException("Invalid Bank Account Info: Account Number is not 10 digits.");
}
else if (tokenTwo.length() < 3){
throw new BankAccountException("Invalid Bank Account Info: Name must be more than 3 letters.");
}
else if (BankAccountProcessor.hasLetter(tokenOne) == true){
throw new BankAccountException("Invalid Bank Account Info: Account Number must be all digits.");
}
else if (BankAccountProcessor.hasDigit(tokenTwo) == true){
throw new BankAccountException("Invalid Bank Account Info: Account Name cannot have digits.");
}
return true;
}

private static boolean hasDigit(String str){
for (char c : str.toCharArray()){
if (Character.isDigit(c)){
return true;
}
}
return false;
}

private static boolean hasLetter(String str){
for (char c : str.toCharArray()){
if (Character.isLetter(c)){
return true;
}
}
return false;
}


}

最佳答案

您在每个循环中使用 = 运算符将 true 分配给 runProgram 变量。结果是 true 所以你的 while 循环将永远循环。使用 == 运算符进行比较:

while (runProgram == true)

或者更简单地说,

while (runProgram)

关于java - 程序循环而不运行完整代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15034890/

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