0

I have having an issue figuring out how to create a linked list of objects created with two inputs. It is not printing as it should be. I wasn't sure how to initiate the initial headObj. I think that might be causing the issue?

public class ContactList {
 public static void main(String[] args) {
  Scanner scnr = new Scanner(System.in);
  int i;
  String name;
  String number;
  int counter;

  ContactNode headObj = new ContactNode(" ");
  ContactNode newObject;
  ContactNode prevObject;
  
  
  prevObject = headObj;
  for (i = 0; i<3; i++){
    
    name = scnr.next();
    number = scnr.next();
    newObject = new ContactNode(name, number);
    prevObject.insertAfter(newObject);
    prevObject = newObject;
  }
  
  newObject = headObj;
  
   counter = 0;
  
  while (newObject != null) {
     counter++;
     System.out.print("Person " + counter + " ");
     newObject.printContactNode();
     newObject = newObject.getNext();
     
   }
  }
}

The result is supposed to be:

Person 1: Roxanne Hughes, 443-555-2864

Person 2: Juan Alberto Jr., 410-555-9385

Person 3: Rachel Phillips, 310-555-6610

But it is printing as:

Person 1 , null

Person 2 Roxanne, Hughes

Person 3 443-555-2864, Juan

Person 4 Alberto, Jr.

1 Answers1

0

You should use nextLine() to scan the current line of characters, because next() method finds and returns the next complete token from your specified Scanner object, which from System.in so it is really depends on how you input the characters.

for more information about Scanner class here is the reference link. and also another reference link from SO about Scanner in that you need to know.

Aleson
  • 332
  • 2
  • 9