First if statement adds numbers to the beginning second if statement adds numbers in the middle (those two works fine). But when i try to add numbers to the end of the list it replaces the old last number with new last number. Lets say i enter 200 the list will look like this 2,5,60,200 Then i enter 340 the list will be 2,5,60,340 instead of 2,5,60,150,200,340. So basically it does not add last number to the list it replaces it. How should i modify my while loop so the last number will be added to the list without replacing the older one?
public void addElementToList()
{
Scanner scan = new Scanner(System.in);
double numToAdd = 0.0;
boolean validNumber = false;double count =0;
do
{
System.out.println("Enter double number");
String str = scan.nextLine();
try
{
numToAdd = Double.parseDouble(str);
validNumber = true;
NumNode aNode = new NumNode(numToAdd);
previous = null;
current = head;
if (current.getNum() > aNode.getNum()) {
aNode.next = head;
head = aNode;
}
//check body
else {
if(current == previous&& previous.getNum()> numToAdd){
aNode.next = head;
head = aNode;
break;
}
if(current.getNum() > numToAdd){// this inserts in middle>
aNode.next = current.next;
current.next = aNode;
break;
}
while(aNode.getNum() > current.getNum() && current.next != null){
previous = current;
current = current.next;
}
previous.next = aNode;
aNode.next = current.next ;
}count++;
}
catch (NumberFormatException nfe)
{
System.out.println("is not a Double number");
}
System.out.println("This number added to list: " + numToAdd);
} while(!validNumber && count<1);
}//end addElementToList()

New Topic/Question
Reply



MultiQuote







|