0

Write a program that reads in characters from the keyboard until it reads a line feed character '\n'. Then have it print the number of vowels, the number of consonants, the number of digits, and the number of other characters. Include the final line feed character in your count of other characters.

I did the most of them but when I type in \n, it dosen't stop. Can anyone give me some help?

import java.util.Scanner;
class characters{
  public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    int v=0;
    int c=0;
    int n=0;
    int o=0;
    char ch;
    do{
      System.out.println("Type in any characters: ");
      System.out.println("Type in \\n to stop. ");
      ch = scan.next().charAt(0);
      if(ch=='\n') {
        o++;
        break;}
      else
      {
        if('a'<=ch && ch<='z')
        {
          if(ch=='a') v++;
          else if(ch=='e') v++;
          else if(ch=='i') v++;
          else if(ch=='o') v++;
          else if(ch=='u') v++;          
          else c++;
        }
        else if('0'<=ch && ch<='9') n++;
        else o++;
      }

    }while(ch!='\n');
    System.out.println("There are "+v+" vowels, "+c+" consonants, "+n+" digits, and "+o+" other characters.");
  }
} 
shadowspawn
  • 3,039
  • 22
  • 26
  • You need to re-read the Javadoc of `Scanner.next()` and if it ready stuff like `\n`. – Tom Sep 22 '19 at 00:35
  • Possible duplicate of [Java using scanner enter key pressed](https://stackoverflow.com/questions/18281543/java-using-scanner-enter-key-pressed) – Yoshikage Kira Sep 22 '19 at 00:55

1 Answers1

0

"Read characters until a line feed is typed" is a just fancy way of saying "read a line of input". So just read a whole line of input and then iterate over it character by character to obtain your counts. Something like this:

int v=0;
int c=0;
int n=0;
int o=0;
System.out.println("Enter a string of characters (Press ENTER when done):");
String line = scan.nextLine();

// OPTION 1 for iterating over the line character by character
for (char ch : line.toCharArray(){
    if ('a' <= ch && ch <= 'z')
        // etc...
}

// OPTION 2 for iterating over line
for (int i = 0; i < line.length(); ++i){
    char ch = line.charAt(i);
    if ('a' <= ch && ch <= 'z') 
         // etc...

}
Kevin Anderson
  • 4,568
  • 3
  • 13
  • 21