• How to modify to a do/while loop in Java

    LowellFeierabend 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));
    
          }
        }
    }
    

    Many of us were struggling with the loops in our coding assignments, so we can find the solution for this problem. The problem is that we are unable to modify the loop as it is already working fine.

    To overcome this problem we have to use a do while loop in java, but the problem is that how to modify it. Here are some tips which will help you to make a do while loop in java.

    Use while loop

    The do while loop is used to check whether a condition is true or false and once the condition is true, it will execute the code again.

    The while loop is the same as the do while loop except it will stop executing the code when the condition is false.

    So, use the while loop whenever you want to execute the code again and don’t modify the code.

    Modify the while loop

    If you want to modify the loop, then you can use the while loop in java as follows.

    [dm_code_snippet background="no" background-mobile="no" slim="yes" bg-color="#abb8c3" theme="dark" language="clike" wrapped="no" height="" copy-text="Copy Code" copy-confirmed="Copied"]

    String name = null;
    
    do {
    
    // Your code
    
    if(condition) {
    
    break;
    
    }
    
    } while(!name.equals("null"));

    [/dm_code_snippet]

    Conclusion:

    So, this is the modification of a do while loop in java. If you are facing any issue regarding this, then you can contact our experts and they will provide you the best solution for your problem.

  • SapnaVishwas 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.

    A better explanation would be that a While loop checks the condition before looping, a do while loop checks the condition after looping

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