[問題] 請教字串寫入問題

看板java作者 (白星羽)時間7年前 (2017/11/12 20:31), 編輯推噓1(104)
留言5則, 3人參與, 7年前最新討論串1/1
不好意思,我是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://www.ptt.cc/bbs/java/M.1510489871.A.02A.html

11/12 21:10, 7年前 , 1F
先close再說吧
11/12 21:10, 1F

11/13 12:28, 7年前 , 2F
1. while裡面的scanner.nextLine() 這行已經讀了一次
11/13 12:28, 2F

11/13 12:28, 7年前 , 3F
所以迴圈裡面的scanner.nextLine()已經是在等下一次輸入了
11/13 12:28, 3F

11/13 12:30, 7年前 , 4F
2. BufferedReader寫完資料,記得使用flush()再close()
11/13 12:30, 4F

11/13 13:15, 7年前 , 5F
謝謝!! :) 一些基本概念錯了...Orz
11/13 13:15, 5F
文章代碼(AID): #1Q23yF0g (java)
文章代碼(AID): #1Q23yF0g (java)