What I have is a simple, convert a temperature in Fahrenheit to Celsius or in Celsius to Fahrenheit. My question: what is the best approach of implementing the while/loops so that the user enters their choice for Celsius to Fahrenheit or vice versa as many times as they want until using a 3 to stop.

package project1;

import java.util.Scanner;

public class Main {


double fahrenheit; 
double celsius; 
int choice;

    public static void main(String[] args) {
      Scanner input = new Scanner(System.in); 
      System.out.print("Please choose one of the following");
      System.out.println (" by entering it's numeric value:  " +
      "1. Fahrenheit to Celsius  " +
      "2. Celsius to Fahrenheit  ");
      int choice = input.nextInt(); 

double enteredTemperature;// temperature asked from user
double convertedTemperature;// temperature converted

      if (choice == 1){
      System.out.println("Enter Temperature in Fahrenheit : ");  

      enteredTemperature = input.nextDouble();  
      convertedTemperature = (5.0/9) * (enteredTemperature - 32);       

      System.out.println("Degrees in celsius: ");  
      System.out.println(convertedTemperature);}  
     
      else if (choice == 2){
      System.out.println("Enter Temperature in C " );  
      enteredTemperature = input.nextDouble();              
      convertedTemperature = (9.0/5)* enteredTemperature + 32; 
      System.out.println("Degrees in F ");
      System.out.println(convertedTemperature);}  
    }
     
}

One good way to do this would be the following

//assuming your Scanner object is called input
do{
   int choice = -1;
   System.out.println(//Print out your choices here);
      if(input.hasNextInt()){
        choice = input.nextInt();
        //call some method that does the calculations here. 
       // the method will take 'choice' as its argument
       //so that it knows what to do. (i.e if choice is 1, 
       //then do Celsius or whatever you wanted.
} else{
   System.out.println("Incorrect choice entered, choice ignored. Enter valid input.");
}

}while(choice != 3)
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.