我应该使用文本文件的输入创建一个字符串数组,但是我无法正确读取文本文件。我把文本文件和程序放在同一个文件夹中,我做错了什么?
package A2;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.PrintWriter;
import java.util.Scanner;
public class a2main {
public static final Scanner SCANNER = new Scanner(System.in);
String[] winners;
public static void main(String[]args) throws FileNotFoundException{ //main method
String teamName = getInput();
createArray();
int wins = calcTeamWins(teamName);
printWins(teamName, wins);
}
public static int calcTeamWins(String TeamName){ //Scans the array and returns team wins
return 0;
}
public static String getInput(){ // Method to get input from user.
System.out.println("Please enter the name of the team you'd like to choose.");
return SCANNER.next();
}
public static String[] createArray() throws FileNotFoundException{ //Method used to create and fill array of winners.
final int ARRAY_LENGTH = 104;
String[] winnerArray = new String[ARRAY_LENGTH];
File WSW = new File("WorldSeriesWinners.txt");
Scanner inputFile = new Scanner(WSW);
for(int i = 0; i < ARRAY_LENGTH-1; i++){
while(inputFile.hasNext()){
winnerArray[i] = inputFile.nextLine();
System.out.println(winnerArray[i]);
}
}
inputFile.close();
return winnerArray;
}
public static void printWins(String TeamName, int Wins){ //Method used to print team anem + wins
System.out.println("The " + TeamName + " have won " + Wins + " World Series.");
}
}
它应该读取的文本文件是WorldSeriesWinners.txt该文件是一行多行文本,每行都有一个字符串。
答案 0 :(得分:0)
执行Java的位置与文件的位置之间存在差异。它不是从该类所在的同一目录中查找的。 p>
由于它已打包,您需要将其添加到路径中。
尝试类似:
new File(System.getProperty("user.dir") + "/A2/" + "WorldSeriesWinners.txt")