Zole95 Zole95 - 6 months ago 8
Java Question

How can I count the number of characters in java without using length?

I'm trying to create a program that will count the number of characters in a word that the user input and I don't want to use the

.length
function.

My problem is that whatever I do the program gives me the answer that there is one more letter 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();
System.out.print(c);
counter++;
} while(c != '\n');
} finally {
counter -=1;
System.out.println("Number of characters: " + counter);
if (cin != null) {
cin.close();
}
}
}
};

Answer

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.print(c);
    counter++;
}
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).

As pointed out by @Jan, in order to be platform independent, you might as well consider checking for \r (which would stop before a \r\n too):

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
Comments