温度转换用户输入错误

时间:2014-02-26 23:44:05

标签: java

我需要这个程序能够使用单个字符而不是指定double来解决用户错误,然后重新提示用户输入适当的double,并且我也被禁止使用hasNextDouble (),这可能吗?

import java.util.Scanner;
public class Temp
{
public static void main(String[] args){
    String prompt = "yes";

    do{
        Scanner input = new Scanner(System.in);
        System.out.println("Enter a number, a space and F to convert from degF to degC and C to convert to degC to degF");
        double degN = input.nextDouble();
        char degU = input.next().toUpperCase().charAt(0);
        while(!(degU == 'C' || degU == 'F')){
            System.out.println("You must enter  F to convert from degF to degC"+
            " and C to convert to degC to degF");
            degU = input.next().toUpperCase().charAt(0);
        }
        if(degU == 'F'){
            double fahrenheit = degN * 9/5 + 32;
            System.out.printf("%.2fF converted to Celsius is %.2fC.", degN, fahrenheit);
        }else{
            double celsius = (degN - 32) * 5/9.0;
            System.out.printf("%.2fF converted to Fahrenheit is %.2fC.", degN, celsius);
        }
        System.out.println("\n"+"Compute another temp - Enter yes or no");
        prompt = input.next().toLowerCase();
    }while(prompt.equalsIgnoreCase("yes"));
  }
}

1 个答案:

答案 0 :(得分:1)

而不是致电nextDouble()致电next()。它将解析字符串。扫描仪类已有详细记录here