[英]Java - Char by char text file reading into 2D array
我正在嘗試返回數組“ 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
方法中,在內循環和StringBuilder中使用returnSeats
seats[0].length
或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();
}
在for (int j = 0; j < seats.length; j++)
,您需要for (int j = 0; j < seats.length; j++)
for (int j = 0; j < seats[i].length; j++)
。
這與多維數組的工作方式有關。 它們是數組的數組。 因此,當您編寫seats.length
,您要詢問有多少行。 調用seats[i].length
詢問第i
行有多少個成員。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.