简体   繁体   English

无法让扫描仪从文件中读取

[英]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.现在我试图用 2 个扫描仪读取这两个文件,然后将名字放在一个数组中,将姓氏放在另一个数组中。

The game is in Object Oriented so there's 3 files:游戏是面向对象的,所以有 3 个文件:

File #1 (App)文件 #1(应用程序)

package tp2;

public class App {

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

File #2 (Game)文件#2(游戏)

package tp2;

public class Game {

    private Level currentLevel;
    private Player player;

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

File #3 (World)文件#3(世界)

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.为了澄清起见,我创建了一个方法来打印两个数组中的名字和姓氏,但是当我执行该方法时它只打印“NULL”。 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()您可以修改 createNamesArray() 函数并去掉 closeNameFiles() 和 openNameFile()

I've updated your World.java (in case you are using java:8)我已经更新了你的 World.java(如果你使用的是 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不过,如果您想按照自己的方式进行操作,我的建议是使用 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.我建议使用 ArrayList,它处理动态大小调整,而数组需要预先定义大小,您可能知道也可能不知道。 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!没什么大不了的!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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