java - 用户输入温度不正确

标签 java eclipse

Repeat the temperature programming project adding a loop that allows the user to continue entering in temperatures, until they enter a Q or q to exit that portion of the program. The user should enter a Q or q to exit and an empty String to continue. (Any other entry should cause the question to be repeated) If the user enters a different letter that F or C(either upper or lower case) for the temperature, print an error message and ask the user to enter the correct temperature scale without asking for a new numeric value.

这是我到目前为止所拥有的......我无法让它读取他们是否输入了 65D 而不是 65C。如果他们输入 D 而不是 F/f 或 C/c,我不知道如何在代码中循环它...

import java.util.Scanner;
public class AssignmentFour {
public static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) {
    // TODO Auto-generated method stub

    System.out.println("Hello, I can convert Fahrenheit to Celsius!");
    System.out.println("Please enter the temperature you want converted.");
    System.out.println("Followed by: 'C/c' or 'F/f'");

    String input2 = keyboard.next();

    do{
        String temp = input2.trim();
        String degreesAsString = temp.substring(0, temp.length()-1);
        double degrees = Double.parseDouble(degreesAsString);

        if(temp.endsWith("C") || temp.endsWith("c")){            
            double degreeF = 9 * degrees / 5 + 32;
            System.out.println(input2 + " is equal to: ");
            System.out.printf("%.2f", degreeF);
            System.out.println(" Fahrenheit.");

        } else if(temp.endsWith("F") || temp.endsWith("f")){
            double degreeC = 5 * (degrees - 32) / 9;
            System.out.println(input2 +" is equal to: ");
            System.out.printf("%.2f", degreeC);
            System.out.println(" Celsius.");

        } else if (temp.endsWith(""));{
            System.out.println("ERROR: Please enter either 'F/f or C/c'.");     
        }
        break;
    } while(!input2.equals(""));

    System.out.println("");
}

最佳答案

只需将 ... = Keyboard.next() 移动到 do-while 循环内即可在循环时读取新的用户输入。此外,您应该删除 break ; 语句当前只是阻止执行任何循环。

关于java - 用户输入温度不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30540025/

相关文章:

java - JBoss 部署错误 - 服务失败

java - 枚举和最终变量有什么区别?

java - 使用父类(super class) java 进行异常处理

java - 我有多个 Elasticsearch 的应该案例,但只有第一个有效

Java - 查找可执行代码行的算法

android - Eclipse 错误中适用于 Android 的 OpenCV 库

java - 将 DataHandler 转换为字符串,并将数据处理程序的内容写入文件

java - Eclipse 安装程序找不到 Java

xml - Eclipse 中缺少 xml 配置选项卡?

android - Eclipse 中的 Joda 时间 : NoClassDefFoundError