gpt4 book ai didi

Java - 逐字 rune 本文件读入二维数组

转载 作者:行者123 更新时间:2023-11-29 09:08:17 25 4
gpt4 key购买 nike

我正在尝试返回数组“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].lengthseats[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();
}

关于Java - 逐字 rune 本文件读入二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13665653/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com