Question about do while loop in java

small question on do while loop

Page 1 of 1

3 Replies - 1604 Views - Last Post: 12 October 2009 - 04:44 PM Rate Topic: -----

#1 araman  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 09-October 09

Question about do while loop in java

Post icon  Posted 12 October 2009 - 04:40 PM

import java.util.Scanner;
public class ExamPractice {

	
	public static void main(String[] args) {
		
	do{	
		Scanner keyboard=new Scanner (System.in);
System.out.println("Please enter a degrees farenheight");
double fahr=keyboard.nextDouble();
double  celc= 5/9.0 *(fahr-32);		
System.out.println("It is "+celc+"degrees celcius");
System.out.println("Would you like to try again?");
String answer=keyboard.next();	
	
	}while(answer.equalsIgnoreCase("yes")); 
	
	}

}




Can someone explain to me what is wrong with this code. The answer in the while condition is underlined error in my compiler. I feel like I'm making a dumb mistake, but I can't put my finger on it.
Thanks

Is This A Good Question/Topic? 0
  • +

Replies To: Question about do while loop in java

#2 macosxnerd101  Icon User is offline

  • Self-Trained Economist
  • member icon




Reputation: 10185
  • View blog
  • Posts: 37,603
  • Joined: 27-December 08

Re: Question about do while loop in java

Posted 12 October 2009 - 04:42 PM

In order for the do statement to test the field answer, you need to declare this variable outside of the loop. Like so:

String answer = "";
do{
   ..code here..
}while(answer.equalsIgnoreCase("Yes"));


Was This Post Helpful? 1
  • +
  • -

#3 Overachiever  Icon User is offline

  • New D.I.C Head

Reputation: 4
  • View blog
  • Posts: 36
  • Joined: 09-September 09

Re: Question about do while loop in java

Posted 12 October 2009 - 04:42 PM

You need to initialize the answer String outside of the do loop.
String answer = "";
do{
  // loop commands...
}while(answer.equals.IgnoreCase("Yes"));


Edit: Once again, beat by macosxnerd....

This post has been edited by Overachiever: 12 October 2009 - 04:44 PM

Was This Post Helpful? 1
  • +
  • -

#4 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8315
  • View blog
  • Posts: 31,836
  • Joined: 06-March 08

Re: Question about do while loop in java

Posted 12 October 2009 - 04:44 PM

And no need to create a new Scanner object inside the loop
create just one before entering the loop
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1