Michael Swartz
Michael Swartz

Reputation: 858

can't properly read in characters using 'Scanner' and '.next().charAt(0)'

Note: I'm running this on Netbeans 8.2 and Windows 7

This program asks for user input, they can enter a character, hit the space bar, or enter a period to stop the program.

1) When I enter a character I get the following error message: "You entered a java.util.Scanner[delimiters=\p{javaWhitespace}+][position=1][match valid=true][need input=false][source closed=false][skipped=false][group separator=\,][decimal separator=\.][positive prefix=][negative prefix=\Q-\E][positive suffix=][negative suffix=][NaN string=\Q?\E][infinity string=\Q8\E]"

2) When I hit the space bar I get no feedback until I enter a period and then I get an error message similar to above but the program does stop.

3) If I enter a period I also get a similar error message but the program does stop.

What I'm expecting is the following: a) if I hit the space bar it returns a message saying I hit the space bar and increments both counters b) if I enter a character then it returns a message stating the entered character and increments the ctr counter c) if a period is entered then it returns a message saying that plus the number of times to to stop the program

I'm guessing the problem is with the keystroke = userInput.next().charAt(0); statement. I thought using userInput.next().charAt(0) would work because they are all single keystrokes and characters. The space is a character, right? Wrong? So if someone could point me in the right direction to fix this that would be appreciated.

/* reads a char, a space, or a period from keyboard, returns user input,
   counts number of spaces and total number of entries */

package ch03_36_exercise_01;
import java.util.Scanner;

public class Ch03_36_Exercise_01 {
  public static void main(String args[]) throws java.io.IOException {

    Scanner userInput = new Scanner(System.in);
    char keystroke;           // character that user enters
    int ctr = 0, spaces = 0;  // num of tries to stop run, num of spaces entered

    do {
      // ask for user input
      System.out.print("Enter a character, or hit the space bar," +
                       " or enter a period to stop: ");
      keystroke = userInput.next().charAt(0);

      if (keystroke == ' ') {
        System.out.println("You entered a space");
        spaces++; // increment space bar count
      }

      else
        System.out.println("You entered a " + keystroke);

      // increment keystroke count
      ctr++;
    }
    while (keystroke != '.');

    System.out.print("It took " + ctr + " tries to stop");

    if (spaces > 0)
      System.out.println(" and you hit the space bar " + spaces + " times\n");

    else
      System.out.println();
  }
}

Upvotes: 0

Views: 742

Answers (1)

Banee Ishaque K
Banee Ishaque K

Reputation: 578

You must use nextLine() instead of next() to read spaces. See more details here : Scanner doesn't see after space. Use isSpaceChar for checking space with a variable. See more details here : Checking Character Properties. The corrected code is....

/* reads a char, a space, or a period from keyboard, returns user input,
   counts number of spaces and total number of entries */
package ch03_36_exercise_01;

import java.util.Scanner;

public class Ch03_36_Exercise_01 {

    public static void main(String args[]) throws java.io.IOException {

        Scanner userInput = new Scanner(System.in);
        char keystroke;           // character that user enters
        int ctr = 0, spaces = 0;  // num of tries to stop run, num of spaces entered

        do {
            // ask for user input
            System.out.print("Enter a character, or hit the space bar,"
                    + " or enter a period to stop: ");
            keystroke = userInput.nextLine().charAt(0);

            if (Character.isSpaceChar(keystroke)) {
                System.out.println("You entered a space");
                spaces++; // increment space bar count
            } else {
                System.out.println("You entered a " + keystroke);
            }

            // increment keystroke count
            ctr++;
        } while (keystroke != '.');

        System.out.print("It took " + ctr + " tries to stop");

        if (spaces > 0) {
            System.out.println(" and you hit the space bar " + spaces + " times\n");
        }
    }
}

Upvotes: 1

Related Questions