我目前正在寫一個小程序,這需要在文本從一個簡單的文件,並將其寫入到另一個文件。輸入文件有點像「madlibs」類型的交易,需要放置令牌,如「」和「」。文件I/O - Java的
文本:
> 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「或其他,並且每個單詞之間有一些空格。
任何幫助表示讚賞,感謝球員和女孩!
啊,這是我在想什麼,這是我測試做一個'的System.out.println(電流)之外;'代碼後您發佈。因此,如下所示: 如果'<'字符在'token'中,那麼執行以下步驟? –
我已經運行你的程序,按照我的建議進行修改,它運行良好。 – Aubin
檢查字符串中是否存在'<'的唯一方法是執行'for'循環?或者是我可以使用像一個特定的功能: '如果(current.contains(「<」))' –