gpt4 book ai didi

java - 为什么我的数组填充不正确?

转载 作者:行者123 更新时间:2023-12-01 18:31:22 25 4
gpt4 key购买 nike

我正在用 Java 编写游戏代码。具体来说,我正在使用由 .txt 文件中的字符填充的字符数组来创建关卡。我的问题是数组没有按应有的方式填充,最后一行仍然为空。我无法解决这个问题,所以任何类型的帮助都会很乐意接受,这是有问题的代码块:

public static void main(String[] args) throws IOException{

char background[][] = new char [14][20];

try {

FileInputStream fileinput = new FileInputStream("background.txt");
int r;
for(int i=0;i<=13;i++){
for(int j=0;j<19;j++){
while((r = fileinput.read()) != -1){
char c = (char) r;
background[i][j] = c;
break;
}
}
}
fileinput.close();
}

catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i=0;i<=13;i++){
for(int j=0;j<=19;j++){
System.out.print(background[i][j]);
}
}
}

整个代码也可以在以下链接中找到:http://pastebin.com/HtwMpsjm这也是 .txt 文件!

最佳答案

你不小心犯了你的条件之一,我已经评论了更改的行。

正如有人在评论中提到的,您可能会发现将循环条件视为 for(int i=0;i<20;i++) 是有益的。而不是for(int i=0i<=19;i++)它使代码更具可读性。

public static void main(String[] args) throws IOException{

char background[][] = new char [14][20];

try {

FileInputStream fileinput = new FileInputStream("background.txt");
int r;
for(int i=0;i<=13;i++){
for(int j=0;j<=19;j++){//<<THIS LINE WAS CHANGED
while((r = fileinput.read()) != -1){
char c = (char) r;
background[i][j] = c;
break;
}
}
}
fileinput.close();
}

catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i=0;i<=13;i++){
for(int j=0;j<=19;j++){
System.out.print(background[i][j]);
}
}
}

关于java - 为什么我的数组填充不正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24020851/

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