Zole95 Zole95 - 2 years ago 115
Java Question

counting number of characters java

I tried to create a program that will count numbers of characters of word that user input, but i don't want to use function .length. My problem is that whatever I do program give me the answer that there is one letter more than I entered.
Here is my code:

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();
} while(c != '\n');
}finally {
counter -=1;
System.out.println("Number of characters: " + counter);
if (cin != null) {

Answer Source

This is because even \n makes your code increment the counter.

One way to change your loop is the following:

while ((c = (char) cin.read()) != '\n') {
System.out.println(); // this is to print the new line character anyway

This performs the test up front instead, so that the counter is not incremented.

Note that c = (char) cin.read() not only assigns the value of the read character to c, but also is an expression which value is the character that has just been read. That's why we can compare this thing to \n.

More generally, the assignment operation (=) is also an expression, which value is the value of the right hand side of the assignment (you can also see it as the value of the variable after the assignment).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download