1

Could someone please explain how to make the input end when I press . without having to press enter and calculate the length without too much advanced stuff since I am just a beginner.

class UserInput//defines class
{//class begins
    public static void main (String[] args) throws IOException
    {//main method begins
        BufferedReader bf = new BufferedReader(newInputStreamReader(System.in));


        //tells the user what the program does
        System.out.println("This program will give you the total number of inputed characters."); 

        // tells the user how to end the program
        System.out.println("To obtain your final number of characters, enter .");       

        System.out.println("");

        //tells user to type in characters
        System.out.println("Enter any characters you want:");
        String input = bf.readLine(); //reads the user input and initializes input


        //initialize and declares variables
        int length = 0;
        length = length + anything.length();

        //outputs total number of characters
        System.out.println("The total number of characters input is " + length);
    }//main method ends
}//class ends

3 Answers3

1

Try reading char by char using System.in.read(). If this doesn't work on your platform, see Why can't we read one character at a time from System.in?

Community
  • 1
  • 1
0

It's not a convention to end commands with "." on command-line -programs. I would suggest you using enter or making a graphical user interface which counts the letters as you type them into textarea using document-listeners or equivalent. The GUI solution is already available at here: show character count in swing gui.

Community
  • 1
  • 1
Kristian
  • 23
  • 5
0

You can try something like this:

Scanner input = new Scanner(System.in);
int totalChars = 0;
// start an endless loop, constantly reading the next entered char from the user
while (true) {
    String next = input.next();
    if (".".equals(next)) {
        // when the user enters ".", exit the loop and stop reading
        input.close();
        break;
    } else {
        // otherwise, just increment the total chars counter
        totalChars++;
    }
}
System.out.println("Total characters: " + totalChars);

The basic idea is to keep reading char by char, until the user chooses to terminate with the "." command. I suggest you swap the BufferedReader for a Scanner. The Scanner class is better suited for reading user input, exposes a more natural and easy to use interface and will help you achieve your goal to the fullest.

Danail Alexiev
  • 7,624
  • 3
  • 20
  • 28