1

I want to be able to output the letter size of each word. So far my code only outputs the letter size of the first word. How do I get it to output the rest of the words?

import java.util.*;

public final class CountLetters {
  public static void main (String[] args) {

    Scanner sc = new Scanner(System.in);
    String words = sc.next();
    String[] letters = words.split(" ");

    for (String str1 : letters) {
       System.out.println(str1.length() ); 
    }   
  } 
}
Kara
  • 6,115
  • 16
  • 50
  • 57
user3376304
  • 13
  • 1
  • 3

3 Answers3

1

Using sc.next() will only let the scanner take in the first word.

 String words = sc.nextLine();
Solace
  • 2,161
  • 1
  • 16
  • 33
1

It's just because next returns only the first word (or also called the first 'token'):

String words = sc.next();

To read the entire line, use nextLine:

String words = sc.nextLine();

What you are doing should work then.

The other thing you can do is go ahead and use next all the way (instead of a split) because Scanner already searches for tokens using whitespace by default:

while(sc.hasNext()) {
    System.out.println(sc.next().length());
}
Radiodef
  • 37,180
  • 14
  • 90
  • 125
0

Iterate over all of the scanner values:

public final class CountLetters {
    public static void main (String[] args) {
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()) {
            String word = sc.next();
            System.out.println(word.length() );
        }
   }
}
deanosaur
  • 621
  • 3
  • 5