Почему моя программа выдает нулевое исключение при чтении этого ввода файла? - PullRequest
1 голос
/ 04 августа 2020

Написание программы для игры в лотки и лестницы путем ввода различных файлов ".txt", чтения их данных и вывода их на виртуальное игровое поле. В программе гораздо больше, однако эта часть меня подвешивает. Всякий раз, когда программа пыталась прочитать файл .txt, она выдает исключение и выводит слово «null».

   public static void main(String[] args) throws IOException {
      int[] boardGame = null;
      Scanner scnr = new Scanner(System.in);
      String fileName;
      String LogFile;
      
      try {
      System.out.println("Enter gameboard data input filename:");
      fileName = scnr.next(); 
     
      boardGame = createGameboard(fileName); //hangup appears to be here and throws Exception
      System.out.println();
      LogFile = writeLogFile(fileName, boardGame);
      if(LogFile == "null") {
      throw new Exception("Program will continue without a log file.");
      }
      else {
         System.out.println("Log file " + LogFile + " successfully created");
      }
      System.out.println();
      } catch (IOException excpt) {
         System.out.println(excpt.getMessage());
         System.out.println("Cannot play without gameboard, so program exiting");
      } catch (Exception excpt) {                 //which is caught here and displays the word null
         System.out.println(excpt.getMessage()); 
      }
      
   }
   
   public static int[] createGameboard(String nameFile) throws IOException {
      int[] gameBoard = null;
      File gameFile = new File(nameFile);
      Scanner inFS = new Scanner(gameFile);
      int boardSize;
      int numLadders = 0;
      int numChutes = 0;
      int index;
      int value;
      
      boardSize = inFS.nextInt();
      boardSize = boardSize;
      gameBoard = new int[boardSize];
      while(inFS.hasNextInt()) {
         index = inFS.nextInt();
         value = inFS.nextInt();
         gameBoard[index] = value;
         if (value > 0) {
            numLadders++;
         }
         else if(value < 0) {
            numChutes++;
         }
         else {
         }        
      }
      
      System.out.println("Gameboard setup with " + (boardSize - 1) + " squares");
      System.out.println("  " + numChutes + " squares have a chute");
      System.out.println("  " + numLadders + " squares have a ladder");
           
      return gameBoard;
      
   }
}
   

Пример используемого файла «.txt»: 31 (boardSize) 3 19 (номер квадрата: перемещать вверх или вниз пробелы 'x') 5 3 11 15 20 9 17-13 19-12 21-12 27-26

Ответы [ 2 ]

0 голосов
/ 04 августа 2020

Извините за отсутствие ответа, но я не могу воспроизвести вашу проблему с помощью предоставленного вами кода.

Я скопировал ваш код, добавил импорт, определение класса и фиктивный метод writeLogFile , затем скопировали образец текстового файла и догадались, как вы его запускали. См. Результат ниже.

Было бы очень полезно, если бы вы сами провели этот эксперимент перед публикацией, потому что таким образом вы можете проверить, действительно ли ваш вопрос отражает проблему и содержит рабочие шаги для воспроизведения:

$ cat foo.txt
31
3 19
5 3
11 15
20 9
17 -13
19 -12
21 -12
27 -26

$ javac Foo.java && java Foo
Enter gameboard data input filename:
foo.txt
Gameboard setup with 30 squares
  4 squares have a chute
  4 squares have a ladder

Log file dummy.txt successfully created

$

Вот Foo.java:

import java.util.*;
import java.io.*;

class Foo {
   public static void main(String[] args) throws IOException {
      int[] boardGame = null;
      Scanner scnr = new Scanner(System.in);
      String fileName;
      String LogFile;
      
      try {
      System.out.println("Enter gameboard data input filename:");
      fileName = scnr.next(); 
     
      boardGame = createGameboard(fileName); //hangup appears to be here and throws Exception
      System.out.println();
      LogFile = writeLogFile(fileName, boardGame);
      if(LogFile == "null") {
      throw new Exception("Program will continue without a log file.");
      }
      else {
         System.out.println("Log file " + LogFile + " successfully created");
      }
      System.out.println();
      } catch (IOException excpt) {
         System.out.println(excpt.getMessage());
         System.out.println("Cannot play without gameboard, so program exiting");
      } catch (Exception excpt) {                 //which is caught here and displays the word null
         System.out.println(excpt.getMessage()); 
      }
      
   }

   static String writeLogFile(String x, int[] y) {
     return "dummy.txt";
   }
   
   public static int[] createGameboard(String nameFile) throws IOException {
      int[] gameBoard = null;
      File gameFile = new File(nameFile);
      Scanner inFS = new Scanner(gameFile);
      int boardSize;
      int numLadders = 0;
      int numChutes = 0;
      int index;
      int value;
      
      boardSize = inFS.nextInt();
      boardSize = boardSize;
      gameBoard = new int[boardSize];
      while(inFS.hasNextInt()) {
         index = inFS.nextInt();
         value = inFS.nextInt();
         gameBoard[index] = value;
         if (value > 0) {
            numLadders++;
         }
         else if(value < 0) {
            numChutes++;
         }
         else {
         }        
      }
      
      System.out.println("Gameboard setup with " + (boardSize - 1) + " squares");
      System.out.println("  " + numChutes + " squares have a chute");
      System.out.println("  " + numLadders + " squares have a ladder");
           
      return gameBoard;
      
   }
}
0 голосов
/ 04 августа 2020

Я думаю, проблема здесь

boardSize = inFS.nextInt();

Проверьте, имеет ли inFS (File) следующий ввод как int или нет.

Исправьте его с помощью

if(inFS.hasNextInt())
     boardSize = inFS.nextInt();
...