2 回答

TA貢獻1799條經驗 獲得超9個贊
建議:不要使用Scanner來讀取文件。它實際上很慢,但很可能適合您的用例。您可能想嘗試以下方法:
Scanner in = new Scanner(System.in);
System.out.println("Enter the record you would like to see: ");
int userChoice = in.nextInt();
// Try With Resources is used here to auto-close the reader.
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
String line;
int counter = 0;
// String[] myArray = {};
while ((line = reader.readLine().trim()) != null) {
if (line.equals("")) {
continue;
}
counter++;
if (counter == userChoice) {
// myArray = line.split("\\s{0,},\\s{0,}");
// System.out.println(Arrays.toString(myArray).replaceAll("[,\\[\\]]", ""));
// If you want to use an Array then un-comment the
// 3 lines above and comment the line below.
System.out.println(line.replace(", ", " "));
break;
}
}
}
catch (FileNotFoundException ex) {
System.err.println(ex.getMessage());
}
catch (IOException ex) {
System.err.println(ex.getMessage());
}

TA貢獻1757條經驗 獲得超8個贊
int userChoice = in.nextInt(); for (int i = 0; i < userChoice; i++) {
我認為你不需要for
循環。只需使用userChoise
像[userChoise-1]
.
添加回答
舉報