Marcus Espoiata Marcus Espoiata - 2 months ago 9
Java Question

Cant understand why i am getting an infinite loop. Java. How to trigger EoF without typing exit

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]);
}
}
}

Answer

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++;
            }