Conner K. McPhee Conner K. McPhee -4 years ago 78
Java Question

Reverse Linked List Issue

I am doing a project for school and my job is to make a LinkedList program that a user can read into a line of ints and use the Linked List functions to print them in reverse.
I have it somewhat working, however, every time I must end the read in from by pressing Ctrl+C. Every... Time...

I'm trying to find a way to stop the scanner read when it reads the int -1.
Whitespace is okay as well. But once it reads -1, i want it to stop
But I cannot find the proper way.

Here is what I have so far:

import java.util.*;
public class ReverseUsingLinkedList
public static void main(String[]args)
System.out.print("Enter a sequence of Integers, -1 to end: ");

LinkedList<Integer> num= new LinkedList<Integer>();
Scanner keyboard = new Scanner(;

num.removeFirst(); //Removes the -1 from the LinkedList

System.out.println("List in reverse :" + num.toString());


I have tried changing the read into hasNext.Int() instead but that cause the read to jump over every other int that I was trying to read. I also tried using an Iterator of some sort but I could not find the proper way to use it.

Any suggestions?

Answer Source

to test if input is -1 and to break if so

  int num = keyboard.nextInt();
  if (num == -1) // or less than 0 ?


Please note @nullpointer very valid comment

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download