我正在尝试返回数组“席位”,它基本上应该从文本文件返回数据 - 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;
}
}
答案 0 :(得分:0)
循环中的轻微问题。更新了以下代码部分:
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
方法中,在内部循环和StringBuilder中使用seats[0].length
或seats[i].length
:
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();
}
答案 1 :(得分:0)
如果您有for (int j = 0; j < seats.length; j++)
,则需要for (int j = 0; j < seats[i].length; j++)
。
这与多维数组的工作方式有关。它们是数组的数组。所以当你写seats.length
时,你会问有多少行。致电seats[i].length
询问行i
中有多少成员。