我目前正在编写一个小程序,它从一个简单的文件中获取文本,并将其写入另一个文件。输入文件有点像“madlibs”类型的交易,带有我需要放置的令牌,如“”和“”。
文本:
> One of the most <adjective> characters in fiction is named
"Tarzan of the <plural-noun>." Tarzan was raised by a/an <noun>
and lives in the <adjective> jungle in the heart of darkest
<place>.
代码:
import java.io.*;
import java.util.*;
public class Story {
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(System.in);
System.out.print("Input file name? ");
String infileName = sc.next();
Scanner input = new Scanner(new File(infileName));
System.out.print("Output file name? ");
String outfileName = sc.next();
PrintStream out = new PrintStream(new File(outfileName));
while (input.hasNext()){
String current = input.next();
System.out.println(current);
int openIndex = current.indexOf("<");
int closeIndex = current.indexOf(">");
current = current.substring(openIndex + 1, closeIndex - openIndex);
System.out.println(current);
if (current.equals("adjective")){
System.out.print("Please enter an adjective: ");
current = sc.next();
out.print(current);
out.print(" ");
} else if (current.equals("plural-noun")){
System.out.print("Please enter a plural noun: ");
current = sc.next();
out.print(current);
out.print(" ");
} else if (current.equals("noun")){
System.out.print("Please enter a noun: ");
current = sc.next();
out.print(current);
out.print(" ");
} else if (current.equals("place")){
System.out.print("Please enter a place: ");
current = sc.next();
out.print(current);
out.print(" ");
} else {
out.print(current);
out.print(" ");
}
}
}
}
这是我似乎遇到的问题:只有用户输入的单词被打印到“out1.txt”或其他任何内容中,并且每个单词之间有许多空格。
任何帮助表示赞赏,感谢男孩和女孩!