i'm new to this and new to java, so please don't be an ahole. But any help would be greatly appreciated.
I've created a very basic program in java for converting from Celsius to Fahrenheit and vice versa. Most of it works exactly as it's supposed to. However, i've hit a bit of a snag.
The program works by prompting the user to enter either "fahrenheit" or "celsius" then asking for a value to be entered so that it can be converted to the other.
The issue i'm having is that when I enter a value other than "fahrenheit" or "celsius", the program terminates. I have it displaying a message telling the user that it doesn't understand the inputted value. But i'm not sure how to send the program back to the beginning of the while loop, rather than terminating the program. Here is the code:
package degreesconversion;
import java.util.Scanner;
public class Degreesconversion
{
public static void main(String[] args)
{
String userinput = "celsius";
double value = 0;
while (userinput.equals("celsius") || (userinput.equals("fahrenheit")))
{
System.out.print("Would you like to convert to celsius or fahrenheit? (Insert in lowercase): ");
Scanner sc = new Scanner(System.in);
userinput = sc.nextLine();
if (userinput.equals("celsius"))
{
System.out.print("Please insert fahrenheit value: ");
value = sc.nextDouble();
value = (value - 32) * 5/9;
System.out.println(value +" celsius");
}
else if (userinput.equals("fahrenheit"))
{
System.out.print("Please insert celsius value: ");
value = sc.nextDouble();
value = value * 9/5 + 32;
System.out.println(value +" fahrenheit");
}
System.out.println("I do not understand!");
}
}
}
I'm not sure what I can add after the last command to re-trigger the while loop so that the user can try and enter the correct command again.
Any help would be great. Cheers!
Aucun commentaire:
Enregistrer un commentaire