所以我编写的代码基本上允许用户输入文本文件的名称来读取输入,看起来像这样。
I wannabe a <job> when I grow up.
Just like my dad.
Life is <adjective> like that!
使用此输入,它会提示用户输入&lt; ...&gt;中单词的madLib。我的代码编译和运行正常,直到我输入一个2字的短语,像警察一样。我想知道是否有一种解析多字短语的方法仍然可以达到相同的结果,因为next()只接受第一个单词,而nextLine()会破坏我的代码。有什么建议?
public static void createMadLib(Scanner console)throws FileNotFoundException{
System.out.print("Input file name: ");
String inputFileName = console.next().toLowerCase();;
File f = new File(inputFileName);
while(!f.exists()){
System.out.print("File not found. Try again: ");
inputFileName = console.next().toLowerCase();
f = new File(inputFileName);
}
System.out.print("Output file name: ");
String outputFileName = console.next();
PrintStream output = new PrintStream(new File(outputFileName));
System.out.println();
Scanner input = new Scanner(new File(inputFileName));
while(input.hasNextLine()){
String line = input.nextLine();
Scanner lineScan = new Scanner(line);
while(lineScan.hasNext()){
String token = lineScan.next();
if(token.substring(0, 1).equals("<") && token.substring(token.length() - 1).equals(">")){
char firstLetter = token.charAt(1);
if(firstLetter == 'a' || firstLetter == 'e' || firstLetter == 'i' ||
firstLetter == 'o' || firstLetter == 'u'){
System.out.print("Please type an " + token.substring(1, token.length() - 1) + ": ");
token = console.next();
}else{
System.out.print("Please type a " + token.substring(1, token.length() - 1) + ": ");
token = console.next();
}
}
output.print(token + " ");
}
output.println();
}
}
答案 0 :(得分:0)
我认为你应该首先阅读整个模板,然后要求替换它包含的每个变量。
更新
或者将模板放在文件中即可。我想在文本中包含这些变量的重点是允许同一模板重用不同的变量值吗?