问题:使用开关盒,编写菜单驱动程序,将温度从华氏温度转换为摄氏温度,反之亦然,以获得错误选项。
我按照以下方式解决了问题:
import java.io.*;
import java.util.*;
class convert {
public static void main(String arg[]) throws IOException {
int ch;
double fah, cel;
Scanner Sc = new Scanner(System.in);
System.out.println("MENU");
System.out.println("1. Fahrenheit to Celsius");
System.out.println("2. Celsius to Fahrenheit");
System.out.println("Enter your choice");
ch = Sc.nextInt();
switch (ch) {
case 1:
System.out.println("enter Fahrenheit values");
fah = Sc.nextDouble();
cel = 5.0 / 9.0 * (fah - 32.0);
System.out.println("Celsius =" + cel);
break;
case 2:
System.out.println("enter Celsius values");
fah = Sc.nextDouble();
cel = 1.8 * (fah + 32.0);
System.out.println("Fahrenheit=" + cel);
break;
default:
System.out.println("vice versa.");
}
}
}
我的方法是否正确?请帮忙。
答案 0 :(得分:0)
您的代码已格式化并且可编辑...下次使用IDE进行编码...
import java. io.*;
import java. util.*;
class Main00
{
public static void main(String arg[]) throws IOException
{
int ch;
double fah, cel;
Scanner Sc= new Scanner (System. in);
System.out.println("MENU");
System.out.println("1. Fahrenheit to Celsius");
System.out.println("2. Celsius to Fahrenheit");
System.out.println("Enter your choice");
ch= Sc.nextInt();
switch (ch)
{
case 1: System.out.print("enter Fahrenheit values");
fah= Sc. nextDouble();
cel= 5.0/9.0*(fah-32.0);
System.out.println("Celsius ="+cel);
break;
case 2 : System.out.print("enter Celsius values");
fah= Sc. nextDouble();
cel=1.8*(fah+32.0);
System.out.println("Fahrenheit="+cel);
break;
default : System.out.println( "vice versa.");
}
}
}
答案 1 :(得分:0)
此代码工作正常。此代码中没有问题。唯一的问题是格式问题。
见下面的代码:
int ch;
double fah, cel;
Scanner Sc= new Scanner (System.in);
System.out.println("Menu");
System.out.println("1. Fahrenheit to Celsius");
System.out.println("2. Celsius to Fahrenheit");
System.out.println("Enter your choice");
ch= Sc.nextInt();
switch (ch)
{
case 1: System.out.println("enter Fahrenheit values");
fah= Sc. nextDouble();
cel= 5.0/9.0*(fah-32.0);
System.out.println("Celsius ="+cel);
break;
case 2 : System.out.println("enter Celsius values");
fah= Sc. nextDouble();
cel=1.8*(fah+32.0);
System.out.println("Fahrenheit="+cel);
break;
default : System.out.println( "vice versa.");