我一直在用 Java 创建一个游戏,我曾经直接在我的代码中编写所有游戏中的文本,如下所示:
String text001 = "You're in the castle.\n\nWhere do you go next?"
但是最近我决定把所有的游戏内文本写在一个文本文件中,并试图让程序读取它们并将它们放入一个字符串数组中,因为文本数量增加了很多,这使我的代码变得非常长。除了一件事外,阅读进展顺利。我在对话中插入了换行符,虽然当我直接在我的代码中编写代码时代码工作正常,但当我尝试从文本文件中读取它们时,它们不再被识别为换行符代码。
它应该显示为:
You're in the castle.
Where do you go next?
但现在显示为:
You're in the castle.\n\nWhere do you go next?
该代码不再将“\n”识别为换行符代码。
这是代码:
import java.io.File;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
Scanner sc;
StringTokenizer token;
String line;
int lineNumber = 1;
String id[] = new String[100];
String text[] = new String[100];
try {
sc = new Scanner(new File("sample.txt"));
while ((line = sc.nextLine()) != null) {
token = new StringTokenizer(line, "|");
while (token.hasMoreTokens()) {
id[lineNumber] = token.nextToken();
text[lineNumber] = token.nextToken();
lineNumber++;
}
}
} catch (Exception e) {
}
System.out.println(text[1]);
String text001 = "You're in the castle.\n\nWhere do you go next?";
System.out.println(text001);
}
}
这是文本文件的内容:
castle|You're in the castle.\n\nWhere do you go next?
inn|You're in the inn. \n\nWhere do you go next?
如果有人告诉我如何解决这个问题,我将不胜感激。谢谢你。
翻过高山走不出你
相关分类