我一直在嘗試很多事情,而我只是準備請求一些幫助。如果這是不夠的信息,請讓我知道。我試過Scanner
,BufferReader
等搜索帖子沒有運氣。如何從src文件夾中將文件加載到ArrayList
我的文件words.txt
就在src目錄中。
import java.io.File; import java.util.ArrayList; import java.util.Random; import java.util.Scanner; /* * CLASS THAT HANDLES GETTING AND SETTING THE SECRET WORD RANDOMLY */ public class secretWord { private ArrayList theWordList; private Scanner scanner; //Used to read the file into the array private Random random; //Generates a random number index for choosing a random array element private int randomIndex; //Holds the random index generated ArrayList theSecretWord= new ArrayList(); //The secret word converted to char[] for use in the program String tempSecretWord; //Secret word selected as string //Constructor: runs methods to create arraylist of words then select a random element for thesecretword public secretWord(){ createArray(); getSecretWord(); } //Creates an ArrayList of words from file private void createArray(){ theWordList= new ArrayList(); String file= getClass().getResource("words.txt").getPath(); File f= new File(file); try{ Scanner scanner= new Scanner(f); while(scanner.hasNext()){ theWordList.add(scanner.nextLine()); } }catch(Exception e){ e.printStackTrace(); }finally{ scanner.close(); } } //Selects a random number from the ArrayList to use as the secret word private void getSecretWord(){ random= new Random(); randomIndex= random.nextInt(theWordList.size()); theSecretWord.add(theWordList.get(randomIndex).toUpperCase()); } //Removes the secretWord and gets a new one for another play void refreshWord(){ theSecretWord.clear(); getSecretWord(); } }
異常在secretWord.createArray(secretWord.java:27)線程 「主」 顯示java.lang.NullPointerException \t \t 在secretWord中。(secretWord.java:21) \t at theFrame。 (theFrame.java:33) \t at theGame.main(theGame.java:6) –
user2576739
當我使用Scanner scanner = new Scanner(new File(words.txt));我得到文件未找到異常。 – user2576739