我正在尝试创建一个程序来计算用户输入的单词中的字符数,但我不想使用.length
功能。
我的问题是,无论我做什么,程序都会给我答案,即比我输入的多一个字母。
这是我的代码:
import java.io.IOException;
import java.io.InputStreamReader;
public class count {
public static void main(String args[]) throws IOException
{
InputStreamReader cin = null;
int counter=0;
try {
cin = new InputStreamReader(System.in);
System.out.println("Enter text: ");
char c;
do {
c = (char) cin.read();
System.out.print(c);
counter++;
} while(c != '\n');
} finally {
counter -=1;
System.out.println("Number of characters: " + counter);
if (cin != null) {
cin.close();
}
}
}
};
最佳答案
这是因为即使 \n
也会使您的代码递增计数器。
更改循环的一种方法如下:
while ((c = (char) cin.read()) != '\n') {
System.out.print(c);
counter++;
}
System.out.println(); // this is to print the new line character anyway
这会预先执行测试,以便计数器不会增加。
注意,c = (char) cin.read()
不仅将读取到的字符的值赋给c
,而且还是一个表达式,其值为刚刚读过的字符。这就是为什么我们可以将这个东西与 \n
进行比较。
更一般地说,赋值操作(=)也是一个表达式,其值是赋值语句右侧的值(也可以将其视为赋值后变量的值)。
正如 @Jan 所指出的,为了独立于平台,您不妨考虑检查 \r
(这将在 \r\n
之前停止)也):
while ((c = (char) cin.read()) != '\n' && c != '\r') {
System.out.print(c);
counter++;
}
System.out.println(); // this is to print the new line character anyway
关于java - java中如何在不使用长度的情况下计算字符数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37148447/