扫描仪输入需要两次,只需要一次

时间:2017-10-20 08:14:43

标签: java

但是我遇到了一个问题,在尝试输入数字时,会发出两次?所以我输入(x)数字,它会向下放空,并要求另一个数字?即使我只输入一个?

(参见输出代码以便更好地理解)

这是我的代码:

import java.util.Scanner;

public class FahrenToCelcius {
    private static Scanner sc;

    public static void main(String[] args) {
        double celsius, fahrenheit;
        System.out.println("Enter your temperatures");
        sc = new Scanner(System.in);
        int[] temperatures = new int[5];
        for(int i = 0; i < 5; ++i) {
            temperatures[i] = sc.nextInt();

            fahrenheit = sc.nextDouble();
            celsius =(fahrenheit-32)*(0.5556);
            System.out.println("Temperature in Celsius:"+celsius); 

        }    
    }
}

输出:

Enter your temperatures
100
100
Temperature in Celsius:37.7808
100
100
Temperature in Celsius:37.7808
100
100
Temperature in Celsius:37.7808

我只希望用户也必须输入一次。帮助

1 个答案:

答案 0 :(得分:2)

您没有使用数组int[] temperatures,因此您可以删除插入其中的语句...

如果您真的想将值保留在数组中。只需使用Double[] temperatures,然后阅读您的扫描仪。

...
fahrenheit = sc.nextDouble();
temperatures[i] = fahrenheit;
...

简而言之,如果您只想输入一个输入,则只能读取扫描仪。

相关问题