处理异常:代码不会终止

时间:2018-12-13 05:28:37

标签: java loops exception exception-handling

我实际上是在进行异常处理,以从具有良好和不良输入的文件中读取输入。

这是Bank.java,它通过readFile()读取文件,并使用read()读取每个帐户并将它们添加到银行列表中。

/**
      Read a file with account numbers and balances and adds the accounts
      to the bank.
      @param filename the name of the file
   */
   public void readFile(String fileName) throws IOException
   {
       File inFile = new File(fileName);
       try(Scanner in = new Scanner(inFile)){
          read(in);
      };

   }

    /**
      Read a file with account numbers and balances and adds the accounts
      to the bank.
      @param in the scanner for reading the input
    */
   private void read(Scanner in)
   {
       while (in.hasNext()){
           BankAccount account = new BankAccount();
           account.read(in);
           addAccount(account);
       }
   }

BankAccount.java:

   /**
      Reads an account number and balance.
      @param in the scanner

   */
   public void read(Scanner in)
   {

       try{
           accountNumber = in.nextInt();
       } catch (NoSuchElementException e){
           accountNumber = 0;
       }

       try{
           balance = in.nextDouble();
       } catch (NoSuchElementException e){
           balance = 0;
       }
   }  

我从中读取数据的文件:

1 5000
2 300
3 4500
4 10000
5 3500
6 5652s
7 12000
8 3498
9 34897
10 3451

它在第6个bankAccount中有一个字母,因此应进行处理,并且accountNumber = 0和余额。但是,调试时实际发生的情况是,它正确读取了所有内容,直到第6个帐户,使该帐户和余额为0,但是,当继续读取时,它将所有下一个accountNumbers和余额都设为0,并永远持续下去!

注意:当我使用正确的输入文件尝试一切正常

出什么问题了?

这是主要内容:

public class BankReader
{
   public static void main(String[] args)
   {
      boolean done = false;
      Scanner in = new Scanner(System.in);

      while (!done)
      {
         System.out.print("Filename: ");
         String filename = in.next();

         try
         {
            Bank bank = new Bank();
            bank.readFile(filename);
            BankAccount highest = bank.getHighestBalance();
            System.out.println("Highest balance account:");
            System.out.println(highest.getAccountNumber()
                  + " " + highest.getBalance());
            done = true;
         }   
         catch (IOException e)
         {   
            System.out.println(e);
         }

      }//while
   }
}

1 个答案:

答案 0 :(得分:0)

in.next()之后添加accountNumber = 0;

如果

nextInt不是int,则不会跳过单词,因此您尝试一次又一次地解析它。