当我输入 Y(尝试再次运行该程序)时,它无法编译。第一次很好。 但第二次尝试不起作用。 我不知道发生了什么事,请帮助我解决这个问题。 该程序就像读取一个座位排列文件并将它们放入一个二维数组中。我正在尝试使用该功能来读取文件并显示座位安排。但只能运行一次。
package Tickets;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
public class Main
{
public static void main(String[] args) throws Exception
{
Scanner sc = new Scanner(new BufferedReader(new FileReader("A1.txt")));
int rows = 0;
int cols = 0;
char again;
Scanner input = new Scanner(System.in);
do
{
displayMenu();
switch(input.nextInt())
{
case 1:
System.out.println("\tReserve seat\t\n");
readFile(sc,rows,cols);
// Get user input
int rowNumber = 0;
char startingSeatNumber = 'Y';
break;
case 2:
System.out.println("Exiting the program");
System.exit(0);
break;
default:
System.err.println("Unrecgnized option");
}
System.out.println("Again?(Y/N)");
again = input.next().charAt(0);
}while (again == 'Y' || again == 'y');
}
public static List<String> readFile(Scanner sc, int rows, int cols) throws Exception
{
List<String> stringList = new ArrayList<>();
while (sc.hasNext())
{
stringList.add(sc.nextLine());
}
rows = stringList.size();
cols = 0;
if (rows > 0 )
{
cols = stringList.get(0).length();
}
// Display current seating.
char[][] auditorium = new char[rows][cols];
char alphabet = 'A';
for (int i = 1; i <= stringList.get(0).length(); i++)
{
System.out.print(" " + alphabet);
alphabet++;
}
System.out.println();
for (int r = 0; r < rows; r++)
{
System.out.print((r+1 ) );
for (int c = 0; c < cols; c++)
{
auditorium[r][c] = stringList.get(r).charAt(c);
System.out.print(auditorium[r][c]+ " ");
}
System.out.println();
}
return stringList;
}
public static void displayMenu()
{
System.out.println("1. Reserve Seats\n2. Exit");
}
}
错误消息:
最佳答案
好的,这就是发生的事情,
您在static void main
方法中创建了Scanner sc
,然后将其传递给readFile。您读取该文件并更新 stringList
列表对象。
1) 迭代一次按其应有的方式进行,因为它是文件的第一次传递,并且 Scanner 对象尚未打开缓冲区。它打开它,读取它并填充stringList
。
2) 在第二次迭代中,传递了相同的扫描仪对象!但该对象已经读取了整个缓冲区!因此以下内容永远不会执行:
while (sc.hasNext())
{
stringList.add(sc.nextLine());
}
然后,当您尝试访问 stringList.get(0).length()
时,会遇到运行时异常(越界),因为它是一个空列表!
请尝试在 readFile
方法中创建本地 Scanner sc = new Scanner(new BufferedReader(new FileReader("A1.txt")));
而不是传递 sc
对象。
关于Java程序再次运行时弹出错误信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60065833/