gpt4 book ai didi

java - 如何使用 Java Scanner 读取特定单词?

转载 作者:行者123 更新时间:2023-12-02 05:09:41 24 4
gpt4 key购买 nike

您好,我有文件名保存,用于在我的 Java 程序中保存游戏。这个文件是这样的

=
B
.
.
.
.
.
W
.
B
.
W
.
B
.
.
.
B
W
W
B
.
.
.
.
.
==
1
0
0
0
0
0
1
0
1
0
1
0
1
0
0
0
1
1
1
1
0
0
0
0
0
===
9
====
2
=====
5

我很困惑,如何读取这个文件,并将每个特定文件的值存储到二维数组和其他变量中,目前我有 5 个变量

arrMove[5][5], arrProc[5][5], forTurn, seconds, totalSeconds

我有这个用于加载游戏的代码,目前我只能从此文件存储 1 个数组
这是有错误的

int x = 0;
int y = 0;
Scanner inFile1 = new Scanner(new File("save.txt"));
while (inFile1.hasNext()) {
// find next line
if (inFile1.hasNext("=")){
ActivityBoard.arrMove[x][y] = inFile1.next();
y++;
if (y > 4) {
y = 0;
x++;
}
}
}
inFile1.close();

这是我的保存游戏

if (e.getSource().equals(SaveMenu)) {
try {
PrintWriter out = new PrintWriter("save.txt");
out.println("=");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
out.println(ActivityBoard.arrMove[i][j]);
}
}
out.println("==");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
out.println(ActivityBoard.arrProc[i][j]);
}
}
out.println("===");
out.println(forTurn);
out.println("====");
out.println(seconds);
out.println("=====");
out.println(TotalTimer.getTime());
out.close();
this.dispose();
System.exit(1);
} catch (FileNotFoundException ex) {
Logger.getLogger(ActivityBoard.class.getName()).log(Level.SEVERE, null, ex);
}
}

我想将此值存储到我的变量中
从分隔符 ===
我想存储到数组 arrMove[5][5]

从分隔符 =====
我想存储到数组 arrProc[5][5]

从分隔符 =======
我想存储到 forTurn

来自分隔符 ====
我想存储到

有人可以帮助我吗?谢谢 :)抱歉我的英语不好。

最佳答案

这不是一个很好的文件格式,但它很容易像这样解析:

public static void main(String[] args) throws Exception {
String s;
Scanner scanner = new Scanner(new File("c:/temp/x.txt"));
while( ! "=".equals((s = scanner.next()))) {
// Ignore - getting to start
}

while( ! "==".equals((s = scanner.next()))) {
// Put in first array
System.out.println("First section: " + s);
}

while( ! "===".equals((s = scanner.next()))) {
// Put in first array
System.out.println("Second section: " + s);
}

// etc...
}

关于java - 如何使用 Java Scanner 读取特定单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27441694/

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