0

input.txtMy text file is being stored into arrays so I can always use if myArray.length < x or if myArray.length > x to exit the system. However that doesn't seem to be working. Is there another way I'm not aware of that can let the user know the text file input is invalid before it crashes or exits the program?

    800 1000 800
    450 845 1200
    1800 250 400
    0 1500 1800
    600 500 1000
    700 1400 1700
    675 400 900

String file = "input.txt";
String text = "";
double [] breakfast = new double [7];
double [] lunch = new double [7];
double [] dinner = new double [7];
try {
    Scanner s = new Scanner(new File(file));
    for (int i = 0;i<7;i++) {
        breakfast[i] = s.nextInt();
        lunch[i] = s.nextInt();
        dinner[i] = s.nextInt();
        if (breakfast.length == 0 || breakfast.length > 7 || breakfast.length < 7) {
            System.out.println("Your file will not work with this program. Please select another.");
            System.exit(0);
        }

text file

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
A. Ramos
  • 3
  • 2
  • 2
    Wouldn't this all depend on the structure of your text file and your code, neither of which you show us? Please improve and clarify your question, showing your pertinent [mcve] code, showing the structure of the file in question. – Hovercraft Full Of Eels Sep 09 '17 at 15:23
  • Thanks for that, now please post the text file as code-formatted text as well, not as an image. Also please tell / show what *specific* errors your current code is generating. – Hovercraft Full Of Eels Sep 09 '17 at 15:33
  • A better solution: use `ArrayList` and don't worry about the length of the data in the file. Even better still -- avoid parallel arrays or parallel ArrayLists, create a class to hold the data for breakfast, lunch and dinner, and create an ArrayList of items of that class. – Hovercraft Full Of Eels Sep 09 '17 at 15:36
  • its giving me "Exception in thread "main" java.util.NoSuchElementException" – A. Ramos Sep 09 '17 at 15:39
  • @bhspencer: consider revising your down-vote since the OP *did* make significant efforts to improve the question. – Hovercraft Full Of Eels Sep 09 '17 at 15:44
  • Have you read the javadoc of Scanner.nextInt()? What does it say about the exceptions it throws? What do you deduce? Also, why do you use double arrays if all your values are integers? And again, what is the content of your test file? – JB Nizet Sep 09 '17 at 15:46
  • @JBNizet It says that exception is thrown when there are no more tokens available. I believe this is thrown because when I test my if statement that says if the array.length is not equal to 7, I test it using a text file that is missing a number. I use the double arrays because later in the program it will calculate the average of the numbers in the array. – A. Ramos Sep 09 '17 at 15:54

0 Answers0