0

I am trying to prompt the user for a series of Integers and stop when the user enter a negative number and i am trying to add the number the users entered in a linked list. I was thinking about using the scanner class but i am having problems with it, and i am not really the great with buffer reader. Please any tips

2
Contributors
1
Reply
2
Views
5 Years
Discussion Span
Last Post by Taywin
0

Scanner class is fine if you accept it as a String using nextLine(). Because you accept it as a string, you can check whether or not the string can be parsed as integer or any type matched your LinkedList node object. If it cannot be matched, reject the input and ask for a new value again. If it can be used, create a new node, add to the list, and ask for a new value again.

int val=0;
Scanner sc = new Scanner(System.in);
while (val>=0) {
  // accept the value
  String str = sc.nextLine();
  // attempt to convert str to an integer and assign to val
  // if success, good, add to the list if the value is not a negative, then let the loop end
  // otherwise, display an error, then let the loop end
}

However, if you expect that a user will always enter an integer, use nextInt() instead, and you do not need to parse it at all but check whether it is OK value to be added to the list.

Edited by Taywin: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.