我正在尝试返回数组“ seats”,该数组本质上应该从文本文件中返回数据-“#”的15x30网格。我尝试了很多事情,但由于对Java的使用经验很少,因此感到沮丧。我的代码可以编译,但是在调用该方法时无法正确打印。
如果有人可以帮助修复构造函数或方法,我将不胜感激...并且如果有任何方法可以避免使用极其复杂的代码,我也将不胜感激。并解释!谢谢!
import java.io.IOException;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.util.*;
public class TicketManager
{
private static int NUMROWS = 15;
private static int NUMCOLS = 30;
private char[][] seats = new char[NUMROWS][NUMCOLS];
private double[] price = new double[NUMROWS];
private int seatsSold;
private int totalRevenue;
public TicketManager()
{
try
{
BufferedReader br = new BufferedReader(new FileReader("seatAvailability.txt"));
String line = br.readLine();
while (line != null)
{
for (int i = 0; i < 15; i++)
{
seats[i] = line.toCharArray();
}
}
}
catch(IOException exception)
{
System.out.println("Error processing file: " + exception);
}
}
public String returnSeats()
{
String result = "";
for (int i =0; i <seats.length; i++)
{
for (int j = 0; j < seats.length; j++)
{
result += seats[i][j] + " ";
}
System.out.println("");
}
return result;
}
}
最佳答案
循环中的轻微问题。下面的代码更新部分:
public TicketManager(){
try{
BufferedReader br = new BufferedReader(new FileReader("seatAvailability.txt"));
for (int i = 0; i < 15; i++)
String line = br.readLine();
seats[i] = line.toCharArray();
}
}catch(IOException exception){
System.out.println("Error processing file: " + exception);
}
}
它将读取15行(行)作为输入。确保在每行中输入准确的
30
字符。也不要在输入行字符中使用空格,例如您每行的输入应类似于X0000xx00xx0xx0xx000xx0xxx0x00
在您的
returnSeats
方法中,在内循环中使用seats[0].length
或seats[i].length
并将StringBuilder用作:public String returnSeats(){
StringBuilder result = new StringBuilder();
for (int i =0; i <seats.length; i++){
for (int j = 0; j < seats[i].length; j++){
//append seat character in the result string
result.append(seats[i][j]);
}
//append new line character in the string in between
result.append(System.lineSeparator());
}
return result.toString();
}