【发布时间】:2014-06-05 21:34:13
【问题描述】:
我有点困惑为什么我需要在这篇文章中使用 do-while 循环。我要做的是计算用户输入字符的次数。当用户键入“.”时,计数应该停止。当我尝试在没有 do-while 的情况下运行程序时,x 的计数乘以 3。我在网上读到控制台输入是行缓冲的。我理解的方式是,一整行是由一个字符创建的,因此实际上还有更多字符?我的理解正确吗?如果可能的话,我能解释一下 do-while 循环吗?
public class readCharLengths {
public static void main(String args[])
throws java.io.IOException {
char typed, ignore;
int x=0;
for ( ; ; ) { //infinite loop to keep reading in values
typed = (char) System.in.read(); //get typed character
do { //confused here
ignore = (char) System.in.read(); //confused here
} while (ignore != '\n'); //confused here
if (typed =='.') break; //break loop when . is typed
x++; //increment x
}
System.out.println("The number of characters is: " + x); //print x
}
}
【问题讨论】:
-
你不需要 do/while 但你还需要显示你的真实代码...... x 未定义,这不会按原样工作。
-
尝试在读取每个
typed和ignore后立即输出,看看你到底忽略了什么。 -
mortsahl,我更新了代码。乔,我尝试在读取这两个变量后输出它们。 “typed”变量接收输入,但“ignore”变量是空白的......这让我想知道为什么我需要do-while!不幸的是,没有它我无法让它工作!
标签: java for-loop increment do-while