• Java modifying to a do/while loop

    Maxim6m0cj Member

    Here’s the code I was provided with and I want to know how to change this into a do/while loop.

    
    import java.text.DecimalFormat;
    
    public class ConversionTable {
       
       public static void main(String args[]){
       
       double cels;
       double fahr;
       DecimalFormat df = new DecimalFormat("0.0");
       
       for (fahr=0; fahr<=300; fahr+=20) { 
       
       cels = (double) (5.0 / 9 * (fahr - 32));
       
       System.out.println("Fahrenheit: " + Math.round(fahr) + " to " + "Celsius: " + df.format(cels));
    
          }
        }
    }
    
  • ShikhaTan Member

    I’m not sure if you understand what you are asking, but here you go:

    int fahr = 0;
    
    do
    {
        cels = (double) (5.0 / 9 * (fahr - 32));
        System.out.println("Fahrenheit: " + Math.round(fahr) + " to " + "Celsius: " + df.format(cels));
    
        fahr += 20;
    }
    while (fahr <= 300);
    

    You don't need a do/while loop here, a while loop or your current loop would work just fine. A do/while loop is a loop that executes ONCE no matter if the condition is false or true. In your case, your while condition will remain true for quite a time.

Viewing 1 reply thread
  • You must be logged in to reply to this topic.