0

I am very new to java and this community. I am looking for someone to possibly be able to explain why my code is going into an infinite loop. I believe it has something to do with my while loop. The program compiles but when I enter a phrase i want for my acronym builder to create the program dosent do anything, it just blinks at the next line. When i press ctrl c to exit, it then shows the acronym.

import java.util.Scanner;
import java.io.*;
import  java.util.*;

public class Acronym{

  public static void main(String[] args) {
    String phraseToChange = "";
    int wordCounter = 0;
    char[] acroynmArray = new char [100];
    Scanner input = new Scanner(System.in);
    System.out.println("This program builds acronyms");
    System.out.println("Enter a phrase:");
    while (input.hasNext() )
    {
      phraseToChange = input.next();
      acroynmArray[wordCounter] = phraseToChange.charAt(0);
      wordCounter++;
    }
    for (int i = 0;i < wordCounter ; i++ )
    {
        System.out.print(acroynmArray[i]);
    }
}
}
  • What input are you giving it? [It doesn't give an infinite loop for me](http://ideone.com/MTiBuW). – Andy Turner Sep 25 '16 at 19:54
  • I will input something like : Google Rocks Socks and then it will just keep blinking on the next line. – Marcus Espoiata Sep 25 '16 at 19:56
  • Do you actually close input? If not, how does it know that there won't be another word? – Andy Turner Sep 25 '16 at 19:57
  • `System.in` will always `hasNext`. You need to exit the loop somehow; maybe check for someone typing `done` or `exit`? – Boris the Spider Sep 25 '16 at 19:57
  • How do i close the input? I type my phrase and press enter – Marcus Espoiata Sep 25 '16 at 19:57
  • You close the standard input stream using `Ctrl-d`. Or do using a stopword like Boris suggests (the downside of which is that you can't enter a phrase containing that word). – Andy Turner Sep 25 '16 at 19:58
  • either add condition other than hasNext() like counter or check if input is 0 then exist or some other conidiotn to break out of loop. – Naruto Sep 25 '16 at 19:59
  • Note that there is a difference between an infinite loop and a method which blocks (like [`Scanner.hasNext()`](https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html#hasNext--)). – Andy Turner Sep 25 '16 at 20:04
  • @Naruto I should add that into my while loop condition? – Marcus Espoiata Sep 25 '16 at 20:04
  • @MarcusEspoiata yes. Add that in your while condition. Another circuit breaker condition . Because hasNext() here will always return true. – Naruto Sep 25 '16 at 20:18
  • Possible duplicate of [How to get out of while loop in java with Scanner method "hasNext" as condition?](http://stackoverflow.com/questions/10490344/how-to-get-out-of-while-loop-in-java-with-scanner-method-hasnext-as-condition) – Tom Sep 25 '16 at 20:18
  • @MarcusEspoiata I added an updated answer for you. Try that. – LumberSzquatch Sep 25 '16 at 21:05

3 Answers3

1

The problem is not truly caused by your while loop but because the fact that scanner will keep asking user new input (system.in stream will always open) until EOF. Therefore, the problem can be solve using StringTokenizer if it's allowed by your professor. Down here is the code example

import java.util.Scanner;
import java.io.*;
import  java.util.*;

public class Acronym{

  public static void main(String[] args) {
    String phraseToChange = "";
    boolean phraseToChange2 = true;
    int wordCounter = 0;
    char[] acroynmArray = new char [100];
    Scanner input = new Scanner(System.in);
    System.out.println("This program builds acronyms");
    System.out.println("Enter a phrase:");
    String nextLine = input.nextLine();
    StringTokenizer st = new StringTokenizer(nextLine, " ");
    while (st.hasMoreTokens())
    {
      phraseToChange = st.nextToken();
      acroynmArray[wordCounter] = phraseToChange.charAt(0);
      wordCounter++;
    }
    System.out.println("reach here");
    for (int i = 0;i < wordCounter ; i++ )
    {
        System.out.print(acroynmArray[i]);
    }
}
}
0

The reason of why your loop never ends it the fact that System.in stream is always open. You should change the condition to while (!phraseToChange.equals("exit")) or something. Then the user will be able to finish the input by sending "exit" string to your program.

Wojtek
  • 1,288
  • 11
  • 16
  • Thankyou for this. But is there any possible way to maybe detect the empty space to exit? The assigment I am working on does not want the user to type exit or anything else other than the phrase. – Marcus Espoiata Sep 25 '16 at 20:13
  • @MarcusEspoiata yes, but you should change `phraseToChange = input.next();` to `phraseToChange = input.nextLine();` and the condition to `while (!phraseToChange.equals(" "))`. – Wojtek Sep 25 '16 at 20:16
  • @MarcusEspoiata It works if after the last word you print a single space in new line and then hit enter. – Wojtek Sep 25 '16 at 20:25
  • i have tested with no luck. – Marcus Espoiata Sep 25 '16 at 20:30
  • @MarcusEspoiata maybe copy the code from here: http://pastebin.com/6X0j1q8d and test it for input: "test[hit_enter][hit_spacebar][hit_enter]". It works in my case, cheers! – Wojtek Sep 25 '16 at 20:34
0

If you don't have to use a while loop with input.hasNext() you can use this. May want to clean up where necessary, but I believe this does what you want.

import java.util.Scanner;
import java.io.*;
import java.util.*;

public class Acronym {

    public static void main(String[] args) {
        String phraseToChange = "";
        int wordCounter = 0;
        char[] acroynmArray = new char[100];
        Scanner input = new Scanner(System.in);
        System.out.println("This program builds acronyms");
        System.out.println("Enter a phrase:");
        String[] line = input.nextLine().split(" ");
        for (int i = 0; i < line.length; i++) {
            phraseToChange = line[i];
            acroynmArray[i] = phraseToChange.charAt(0);
            wordCounter++;
        }
        for (int i = 0; i < wordCounter; i++) {
            System.out.print(acroynmArray[i]);
        }
    }
}

Sample build output:

 run:
    This program builds acronyms
    Enter a phrase:
    Google Rocks Socks
    GRSBUILD SUCCESSFUL (total time: 4 seconds)

Code snippet that causes the change:

 String[] line = input.nextLine().split(" ");
            for (int i = 0; i < line.length; i++) {
                phraseToChange = line[i];
                acroynmArray[i] = phraseToChange.charAt(0);
                wordCounter++;
            }

Alternatively you could use this:

public static void main(String[] args) {
    String phraseToChange = "";
    int wordCounter = 0;
    char[] acroynmArray = new char [100];
    Scanner input = new Scanner(System.in);
    System.out.println("This program builds acronyms");
    System.out.println("Enter a phrase:");
    String line = input.nextLine();   // Obtain user entered line
    acroynmArray[0] = line.charAt(0); // First letter is known; set it
    wordCounter++;                    // increment wordCounter
    //Loop the characters in the retrieved line
    for(int i = 0; i < line.length(); i++){
     // If it's whitespace then we know the next character must be the letter we want
        if(Character.isWhitespace(line.charAt(i))){ 
            acroynmArray[wordCounter] = line.charAt(i+1); // Set it
            wordCounter++;
        }
    }

But as Tom said in my deleted post, this is quite fragile code. It works, until it doesn't, as in it wouldn't take much to break it as it doesn't handle trailing and starting whitespaces

LumberSzquatch
  • 1,054
  • 3
  • 23
  • 46
  • Holy moly! This works! Can you explain what you changed please? Sadly, my professor said no split statements. – Marcus Espoiata Sep 25 '16 at 20:23
  • So instead of using a while loop, I just obtained the user entered line via `input.nextLine()` and then I call `split()` on the same line splitting it at `" "` which is just whitespace. This returns an array of the words, and then all you have to do is iterate the array and for each word do what you need to with it. – LumberSzquatch Sep 25 '16 at 20:25
  • @MarcusEspoiata I added the exact snippet I used to get it working just so it's more isolated. – LumberSzquatch Sep 25 '16 at 20:26
  • @MarcusEspoiata Aww, I just saw your statement for what your professor said. Been there man. Well feel free to accept someone else's answer if it meets your requirements. – LumberSzquatch Sep 25 '16 at 20:28
  • @MarcusEspoiata I'd use Khanh Duc Tran's answer, since it doesn't use split. Better than the second answer I posted. – LumberSzquatch Sep 25 '16 at 21:16