作者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/cn.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