public static void main(String[] args) {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int charCount = 0;
int wordCount = 0;
int lineCount = 0;
String line;
try {
while( (line = in.readLine()) != null ) {
System.out.println(line);
lineCount++;
charCount += line.length();
String[] words = line.split("\\W");
wordCount += words.length;
}
System.out.println("charCount = " + charCount);
System.out.println("wordCount = " + wordCount);
System.out.println("lineCount = " + lineCount);
} catch (IOException e) {
e.printStackTrace();
}
}
直截了当:如何退出上述while循环?我已经阅读了另一个问题,当没有剩余的行要读取时,readLine()返回null,但是如何使用Eclipse的控制台呢?
我能设法打破循环的唯一方法是添加案例,例如
if(line.length() == 2 || line.equals("exit")))
break;
答案 0 :(得分:0)
如果您只是想读一行,为什么还需要while循环? 或者如果你想要多个输入,那么你应该指定在第一个readline()中输入多少输入; 否则我希望下面的代码将解决您的问题:)
公共类TestRandomArray {
public static void main(String[] args) {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int charCount = 0;
int wordCount = 0;
int lineCount = 0;
try {
String line = in.readLine();
lineCount++;
charCount += line.length();
String[] words = line.split(" ");
wordCount += words.length;
System.out.println("charCount = " + charCount);
System.out.println("wordCount = " + wordCount);
System.out.println("lineCount = " + lineCount);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}