简体   繁体   中英

Can't get Scanner to read from file

I am making a Battle Royale game in command line, and I have the bots' First Names and Last Names in two text files. Now I'm trying to read from these two files with 2 Scanners, then put the First names in one array, and the Last names in another array.

The game is in Object Oriented so there's 3 files:

File #1 (App)

package tp2;

public class App {

    public static void main(String[] args) throws InterruptedException {
        Game game = new Game();
        game.start();
    }    
}

File #2 (Game)

package tp2;

public class Game {

    private Level currentLevel;
    private Player player;

    public void start() throws InterruptedException {
        World.createNameArrays();
        World.printNamesArrays();              
    }
}

File #3 (World)

package tp2;

import java.io.*;
import java.util.*;
import java.util.concurrent.TimeUnit;

public class World {
    private static final int MAX_PLAYERS = 42;
    private static String firstNamesArray[] = new String[MAX_PLAYERS];
    private static String lastNamesArray[] = new String[MAX_PLAYERS];
    private static Player players[] = new Player[MAX_PLAYERS];

    private static Scanner scannerFirstNames;
    private static Scanner scannerLastNames;

    public static void printNamesArrays() {
        System.out.println("");
        System.out.println("First names available");
        System.out.println("---------------------");
        for (int i = 0; i < MAX_PLAYERS; ++i) {
            System.out.println(firstNamesArray[i]);
        }
        System.out.println("");
        System.out.println("Lats names available");
        System.out.println("---------------------");
        for (int i = 0; i < MAX_PLAYERS; ++i) {
            System.out.println(lastNamesArray[i]);
        }
    } 

    public static void createNameArrays() {        
        openNameFiles();
        int i = 0;
        while (scannerFirstNames.hasNext() && scannerLastNames.hasNext()) {
            System.out.println("**********Test*************");
            firstNamesArray[i] = scannerFirstNames.nextLine();
            lastNamesArray[i] = scannerLastNames.nextLine();
            ++i;            
        }
        closeNameFiles();
    }

    public static void closeNameFiles() {
        scannerFirstNames.close();        
        scannerLastNames.close();
    }

    public static void openNameFiles() {
        try {
            scannerFirstNames = new Scanner(new File("firstnames.txt"));
        } catch(FileNotFoundException e) {
            System.out.println("Error! File not found.");
        }
        try {
            scannerLastNames = new Scanner(new File("lastnames.txt"));
        } catch(FileNotFoundException e) {
            System.out.println("Error! File not found.");
        }        
    }
}

For clarification, I made a method to print the First names and Last names from the two arrays, but it just prints "NULL" when I execute the method. That would just mean that the Scanners can't read the two files for some reasons...

You can modify the createNamesArray() function and get rid of closeNameFiles() and openNameFile()

I've updated your World.java (in case you are using java:8)

public class World {

  private static final int MAX_PLAYERS = 42;
  private static String firstNamesArray[] = new String[MAX_PLAYERS];
  private static String lastNamesArray[] = new String[MAX_PLAYERS];
  private static int firstNameEntriesInFile;
  private static int lastNameEntriesInFile;

  public static void printNamesArrays() {
    System.out.println("");
    System.out.println("First names available");
    System.out.println("---------------------");
    for (int i = 0; i < MAX_PLAYERS && i < firstNameEntriesInFile; ++i) {
      System.out.println(firstNamesArray[i]);
    }
    System.out.println("");
    System.out.println("Lats names available");
    System.out.println("---------------------");
    for (int i = 0; i < MAX_PLAYERS && i < lastNameEntriesInFile; ++i) {
      System.out.println(lastNamesArray[i]);
    }
  }

  public static void createNameArrays() {
    try {
      String[] fNames = Files.lines(new File("fullpath/firstname.txt").toPath()).toArray(String[]::new);
      if (fNames.length == 0) {
        throw new RuntimeErrorException(null, "no first name entry found in the given file");
      } else {
       firstNameEntriesInFile=fNames.length;
       firstNamesArray=fNames;
      }
      String[] lNames = Files.lines(new File("fullpath/lastname.txt").toPath()).toArray(String[]::new);
      if (lastNamesArray.length == 0) {
        throw new RuntimeErrorException(null, "no last name entry found in the given file");
      }else {
        lastNameEntriesInFile=lNames.length;
        lastNamesArray=lNames;
       }
    } catch (IOException e) {
      e.printStackTrace();
      System.out.println("file can't be accessed: cause " + e.getMessage());
    }
  }
}

Still, if you would like to do it your way my suggestion will be to use FileReader

I would recommend using an ArrayList, which handles dynamic sizing, whereas an array will require a defined size up front, which you may or may not know. Looking at your code I see you have already defined the size.

BufferedReader in = new BufferedReader(new FileReader("fullpath/firstnames.txt"));
String str;

List<String> list = new ArrayList<String>();
while((str = in.readLine()) != null){
    list.add(str);
}

firstNamesArray = list.toArray(new String[list.size()]);

similarly for last name array.

Also, it's not wise to use static first and foremost reason being thread safety second Obj-Oriented concepts.

Don't worry we all were in your shoes one day, then we learned with time. Not a big deal!

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