简体   繁体   中英

catch error while reading file from args (java)

Can someone please explain to me why I'm getting the catch error?

I am trying to read values (numbers) from the file I passed in args.

And I do not quite understand where the problem comes from.

import java.util.Scanner;//               Import the Scanner class to read text files
import java.io.File;//                    Import the File class
import java.io.FileNotFoundException;//   Import this class to handle errors
import java.io.*;

public class main extends GeneralMethods {
  public static void main(String[] args) {
    if (args.length <= 1 || args.length > 2) {
      println("Error, usage: software must get two input files");
      System.exit(1);
    }

    String file_name1 = args[0]; // data to insert
    String file_name2 = args[1]; // data to check

    File data_to_insert = new File(file_name1);
    File data_to_check = new File(file_name2);

    Scanner input = new Scanner(System.in); // Create a Scanner object

    println("Enter hashTable size");
    int hashTable_size = input.nextInt(); // Read hashTable_size from user

    println("Enter num of hashing function");
    int num_of_has = input.nextInt(); // Read num of hashing from user

    hashTable T = new hashTable(hashTable_size);
    println("hashTable before insert values\n");
    T.printHashTable();
    input.close();

    int i = 0;
    try {
      input = new Scanner(data_to_insert);
      String data;
      while ((data = input.next()) != null) {
        T.set(i, Integer.parseInt(data));
        i++;
      }
      input.close();
    } catch (Exception e) {
      System.out.println("\nError: Reading, An error occurred while reading input files. Check your input type");
      e.printStackTrace();
    }
    T.printHashTable();
  }
} 

this is my output

Which prints the catch error

hashTable before insert values

[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]

Error: Reading, An error occurred while reading input files. Check your input type
java.util.NoSuchElementException
        at java.base/java.util.Scanner.throwFor(Scanner.java:937)
        at java.base/java.util.Scanner.next(Scanner.java:1478)
        at main.main(main.java:36)
[1,2,3,4,5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]

In this line,

while ((data = input.next()) != null) 

The next() method of Scanner does not return null if it has no more data, instead it throws the NoSuchElementException you are getting.

Use this instead to check for more data:

while ((input.hasNext()) {
    data = input.next();
    //...
}

Method hasNext() returns true or false as you would expect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM