-2

I updated my code from previous suggestions, and it is only reading the first word in my sentence, any suggestions on how to get it to read the whole sentence? (I have to use a for loop)

import java.util.Scanner;

public class CountCharacters {
public static void main(String[] args) {
    Scanner in = new Scanner(System.in);

    char letter;
    String sentence = "";
    System.out.println("Enter a character for which to search");
    letter = in.next().charAt(0);
    System.out.println("Enter the string to search");
    sentence = in.next();

    int count = 0;
    for (int i = 0; i < sentence.length(); i++) {
        char ch = sentence.charAt(i);
        if (ch == letter) {
            count ++;
        }
    }
    System.out.printf("There are %d occurrences of %s in %s", count,
            letter, sentence);

}
}

Output: Enter a character for which to search h Enter the string to search hello how are you There are 1 occurrences of h in hello

4

2 Answers 2

1

It's a little tricky here. You will need two readLines().

System.out.println("Enter a character for which to search");
letter = in.nextLine().charAt(0);
System.out.println("Enter the string to search");
sentence = in.nextLine();

Scanner.next() only reads one word and does not finish the line.

// Assume input: "foo" [enter] "test this yourself!"
Scanner.next(); // "foo"
Scanner.nextLine(); // EMPTY STRING!
Scanner.nextLine(); // "test this yourself!"
1

Your scanner only reads the next word (in.next()). If you want to read a whole line, you should use the method nextLine of your Scanner.

If you expect the user to input several values, you will have to read accordingly from that Scanner (so you will also have to read the newline from the answer of the first question you are asking the user).

I will not give you code to fix the issue, this is just meant as a pointer in the right direction. It would be very good if you familiarize yourself with those standard classes. Sun/Oracle have done a very good job in documentation. So the first look should always be in the Java Doc of the classes you are using.

Here is the doc for the class Scanner.

2
  • Warn about the empty line that you will get if you don't eat the newline after the next(). Oct 25, 2013 at 5:49
  • Didn't want to spoil any code, but you are right, that warning is appropriate. Added it
    – Matthias
    Oct 25, 2013 at 5:57

Not the answer you're looking for? Browse other questions tagged or ask your own question.