0

The code works the first time through. But after that, the output doesnt work. The main goal of this is to create an infinite loop, of asking a user for a phrase, then a letter. Then, to output the number of occurences of the letter in the phrase. Also - - how would i go about breaking this loop by entering a word?

Scanner in = new Scanner(System.in);

for (;;) {

    System.out.println("Enter a word/phrase");
    String sentence = in.nextLine();

    int times = 0;

    System.out.println("Enter a character.");
    String letter = in.next();

    for (int i = 0; i < sentence.length(); i++) {
        char lc = letter.charAt(0);
        char sc = sentence.charAt(i);
        if (lc == sc) {
            times++;
        }
    }
    System.out.print("The character appeared:" + times + " times.");
}
Pshemo
  • 122,468
  • 25
  • 185
  • 269
N00B
  • 3
  • 2

3 Answers3

2

Remove the for loop and replace it with a while.

The while loop should check for a phrase and it will drop out automatically when the phrase is met.

So something like

while (!phraseToCheckFor){
// your code
}

This sounds like homework so I won't post all the code but this should be enough to get you started.

griegs
  • 22,624
  • 33
  • 128
  • 205
0

If you need an infinite loop, just do this:

for(;;) {  //or while(true) {
    //insert code here
}

You can break the loop by using the break statement, for example like this:

for(;;) {
    String s = in.nextLine();
    if(s.isEmpty()) {
        break; //loop terminates here
    }
    System.out.println(s + " isn't empty.");
}
kviiri
  • 3,282
  • 1
  • 21
  • 30
0

In order for your program to run correctly, you need to consume the last new line character. You can do this by adding a call to nextLine. Working example,

public static void main(String[] args) {

        Scanner in = new Scanner(System.in);

        for (;;) {

            System.out.println("Enter a word/phrase");
            String sentence = in.nextLine();

            if (sentence.trim().equals("quit")) {
                break;
            }

            int times = 0;


            System.out.println("Enter a character.");
            String letter = in.next();

            for (int i = 0; i < sentence.length(); i++) {
                char lc = letter.charAt(0);
                char sc = sentence.charAt(i);
                if (lc == sc) {
                    times++;
                }
            }
            System.out.println("The character appeared:" + times + " times.");
            in.nextLine();//consume the last new line
        }
    }
melc
  • 11,523
  • 3
  • 36
  • 41
  • 1
    Don't give OP ready code. Let him improve his programming abilities by showing his mistakes, not correcting them. – Pshemo Nov 03 '13 at 21:39