Java program using PrintWriter and FileWriter...?

2008-12-08 6:15 am
import java.io.*;
import java.util.*;

class Keyboard2 {

public static void main(String[] args) throws IOException {

FileWriter fw= new FileWriter("datafile.txt");
PrintWriter pw= new PrintWriter(fw);
Scanner key= new Scanner(System.in);
System.out.println("Please enter a string");
String s1= key.nextLine();
pw.print("s1");
System.out.println();
System.out.println("Please enter an int");
int i= key.nextInt();
pw.print("i");
System.out.println();
System.out.println("Please enter another string");
String s2= key.nextLine();
pw.print("s2");
System.out.println();
System.out.println("Thank you, program ending...");
pw.close();
fw.close();

}
}

For some reason, when I run this, it won't let me enter anything for the second string. Help please?

回答 (3)

2008-12-08 7:42 am
✔ 最佳答案
I'm not sure why you chose to use Scanner over something else, but I'd suggest you use BufferedReader to get your inputs... well, if it's not restricted (like if the problem is a school work assignment of some sort). Scanner is more suitably used parsing a fixed string. If you insist on using the Scanner class, you'll have to re-generate the Scanner object each time you want to read in new inputs.

Hope it helps.
2016-05-29 4:34 pm
Don't use System.exit() to end a program like this. Since there is only one thread, the program will end automatically when the main() method returns.
2008-12-08 6:48 am
I think it is your PrintWriter pw = new PrintWriter(fw, true); so it will auto-flush. I don't really know, I don't use PrintWriter but I happened to noticed in the Java API you switch auto-flush.


收錄日期: 2021-05-01 01:04:02
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20081207221527AA4XEQ4

檢視 Wayback Machine 備份