为什么我的java程序不工作?它不允许我输入我的字符串语句比例。

时间:2015-01-21 15:21:35

标签: java java.util.scanner

这是我写的将华氏转换为Celcius的代码,反之亦然。老师说我们必须使用switch语句。

import java.util.Scanner;
public class hope 
{
    public static void main(String[]args)
    {
        Scanner keyboard = new Scanner(System.in);
        System.out.println("Enter the number of degrees: ");
        double degrees = keyboard.nextDouble();
        System.out.println("Enter the scale: ");
        String scale = keyboard.nextLine();

        switch(scale)
        {
        case "F":
        case "f":
            double fahrenheit = (degrees - 32) * .5556;
            System.out.println(degrees + scale + " equals " + fahrenheit + " degrees celcius");
            break;
        case "C":
        case "c":
            double celcius = (degrees + 32) * 1.8;
            System.out.println(degrees + scale + " equals " + celcius + " degrees Fahrenheit");
            break;

        default:
            System.out.println("I don't know what you're talking about. Chaw. ");
            break;

        }
    }

}

问题是当我运行程序时,程序允许我输入度数,然后显示print语句,然后只是跳转到默认情况而不允许我输入比例。

3 个答案:

答案 0 :(得分:3)

您需要使用新行。 Scanner.nextDouble()只会将下一个令牌读为double,而不会使用行终止符。在阅读双精度后添加keyboard.nextLine()

double degrees = keyboard.nextDouble();
keyboard.nextLine();

或在输入行使用Double.parseDouble(String)

String degreesString = keyboard.nextLine();
double degrees = Double.parseDouble(degreesString);

答案 1 :(得分:2)

您输入的双倍之后将被keyboard.nextLine();

消耗

所以你必须再次进入keyboard.nextLine();

double degrees = keyboard.nextDouble();
keyboard.nextLine();
System.out.println("Enter the scale: ");
String scale = keyboard.nextLine();

答案 2 :(得分:0)

如果扫描仪输入实用程序不是必须的,我建议使用BufferedReader。

package com.tempcalculator;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

public class Main {

public static void main(String[] args) {
    String degrees = getInput("Degrees?");
    String scale = getInput("Scale?");

    switch (scale.charAt(0)) {
        case 'F':
        case 'f':
            double fahrenheit = (Double.parseDouble(degrees) - 32) * .5556;
            System.out.println(degrees + scale + " equals " + fahrenheit + " degrees Celsius");
            break;
        case 'C':
        case 'c':
            double celsius = (Double.parseDouble(degrees) + 32) * 1.8;
            System.out.println(degrees + scale + " equals " + celsius + " degrees Fahrenheit");
            break;
        default:
            System.out.println("Whoops! Error 404: Requested scale was not found. ");
            break;
    }
}


public static String getInput(String prompt) {
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

    System.out.print(prompt);
    System.out.flush();

    try {
        return in.readLine();
    } catch (IOException e) {
        return "Error: " + e.getMessage();
    }

}

}