Will Ferguson Will Ferguson - 4 months ago 9
Java Question

Removing last string from being printed in Java

I made a program that stores user inputted strings to a queue and then prints out the whole thing, but I am having some issues with blocking the string ''end'' from being printed out when printing the string queue.

public class Test {

protected static String testinfo;
Test() {
testinfo= "blank";
}

public static void setTest(String newInfo){
testInfo = newInfo;
}

public static String getTest(){
return testInfo;
}

private static Scanner input = new Scanner(System.in);

public static void main(String[] args) {
Queue<String> queue = new LinkedList<String>();
String newInfo;

System.out.println("Inset information for the test or quit by typing end ");

while (true) {
System.out.println("Insert information: ");
newInfo = input.nextLine();

Test.setTest(newInfo);

queue.offer(Test.getTest());

if (newInfo.equals("end")){
break;
}
}

while(queue.peek() !=null) {
String x = queue.poll();
if(x.contains("end")) {
queue.remove("end");
}
System.out.println(x + " ");
}
}
}

Answer

In while loop, you have already offered the user entered String - end to the queue, before you check for break condition. As a matter of fact, the String - end is enqueued.

Re-arranging the statements in while loop should solve the issue you are facing

    while (true) {
        System.out.println("Insert information: ");
        newInfo = input.nextLine();
        if (newInfo.equals("end")){
            break;
        }
        Test.setTest(newInfo);
        queue.offer(Test.getTest());
    }

Note: I din't refactor other parts of your code.