Tuesday, 10 September 2013

Having trouble using while loop in java

Having trouble using while loop in java

I am trying to make a while loop that asks user input. If user types "hi"
it will print "hello" and if user types "done" it will end the loop , but
if user types anything else or integer it will say "type either hi or
done.". The code is below:
public static void main(String[] args){
Scanner input = new Scanner(System.in);
while(!(input.nextLine()).equals("done")){
if((input.nextLine()).equals("hi"))
{
System.out.println("Hello");
}
else
{
System.out.println("Type hi or done");
}
}
}
But with this code it is asking user input two times before it showing the
result. What is the problem and how to deal with it in the most effective
way?

No comments:

Post a Comment