作者starlichin (白星羽)
看板java
標題[問題] 請教字串寫入問題
時間Sun Nov 12 20:31:08 2017
不好意思,我是Java初學者,自修的過程中遇到書上一個題目,
要寫出一個程式,讓使用者輸入字串,然後將字串寫入txt文字檔。
另外,再寫一個搜尋的功能,找出此txt檔中,特定字串的出現次數。
我目前還卡在第一階段,讓使用者輸入字串並寫入文字檔。
以下是我目前寫的,但似乎運行結果無法創建文字檔,
然後使用者輸入的loop也無法像我想要的,輸入"STOP"就跳出。
想請問各位大大,我的問題出在哪裡? 感謝! <(_ _)>
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class TextSearch {
public static void main(String[] args) throws IOException {
//Create new file named "myText"
File myFile = new File("myText.txt");
String EndingInputKW = "STOP";
System.out.println("Input String, or enter STOP to complete
inputting: ");
//Input strings until enter "STOP"
ArrayList<String> stringInputArrayList = new ArrayList<String>();
Scanner scanner = new Scanner(System.in);
while (!scanner.nextLine().equals(EndingInputKW)) {
stringInputArrayList.add(scanner.nextLine());
}
//Write Strings into "myText" File
BufferedWriter bufferedWriter = new BufferedWriter(new
FileWriter(myFile));
for (int i = 0; i < stringInputArrayList.size(); i++) {
bufferedWriter.write(stringInputArrayList.get(i));
}
}
}
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 36.225.110.209
※ 文章網址: https://webptt.com/m.aspx?n=bbs/java/M.1510489871.A.02A.html
1F:→ pttworld: 先close再說吧 11/12 21:10
2F:推 pipi99: 1. while裡面的scanner.nextLine() 這行已經讀了一次 11/13 12:28
3F:→ pipi99: 所以迴圈裡面的scanner.nextLine()已經是在等下一次輸入了 11/13 12:28
4F:→ pipi99: 2. BufferedReader寫完資料,記得使用flush()再close() 11/13 12:30
5F:→ starlichin: 謝謝!! :) 一些基本概念錯了...Orz 11/13 13:15