2

我正在尝试返回数组“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;
    }
}
4

2 回答 2

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方法中,使用seats[0].lengthorseats[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();
}
于 2012-12-02T01:51:43.373 回答
0

你有的地方for (int j = 0; j < seats.length; j++),你就需要有for (int j = 0; j < seats[i].length; j++)

这与多维数组的工作方式有关。它们是数组的数组。所以当你写的时候seats.length,你是在问有多少行。呼叫seats[i].length询问有多少成员排成一排i

于 2012-12-02T01:52:07.823 回答