寻找高温和低温(JAVA)第一作业

时间:2014-01-23 14:24:06

标签: java temperature

我似乎无法弄明白。我需要问用户3个花车,得到它。高低部分的输出有问题。任何帮助都会很棒!

package temp;
import java.util.Scanner;
/**
 *
 * @author Pherman
 */
public class Temp {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
         float temp1;
         float temp2;
         float temp3;
    float highTemp;
    float lowTemp;

    System.out.print("Please enter your first temperature");
        temp1=scan.nextFloat();
    System.out.print("Please enter your second temperature");
        temp2=scan.nextFloat();
    System.out.print("Please enter your third temperature");
        temp3=scan.nextFloat();

    }

 }

4 个答案:

答案 0 :(得分:2)

这是给你的提示。

http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html

float highTemp = Math.max(temp1, Math.max(temp2, temp3); // high

float lowTemp = Math.min(temp1, Math.min(temp2, temp3); // low

float middleTemp = (temp1 + temp2 + temp3) - highTemp - lowTemp; // middle

在此方法中,无需使用ifswitcharraysort

答案 1 :(得分:2)

我会使用数组,Arrays.sort(float[])就像这样

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    float[] temp = new float[3];

    for (int i = 0; i < temp.length; ) {
        System.out.printf("Please enter your temperature #%d ", i);
        if (scan.hasNextFloat()) {
            temp[i] = scan.nextFloat();
            i++;
        } else {
            scan.next();
        }
    }
    java.util.Arrays.sort(temp);
    System.out.println("Low = " + temp[0]);
    System.out.println("High = " + temp[temp.length - 1]);
}

答案 2 :(得分:2)

将集合用于min / max

List<Float> myList = new ArrayList<Float>();

System.out.print("Please enter your first temperature");
myList.add(scan.nextFloat());
System.out.print("Please enter your second temperature");
myList.add(scan.nextFloat());
System.out.print("Please enter your third temperature");
myList.add(scan.nextFloat());

System.out.println(Collections.min(myList));
System.out.println(Collections.max(myList));

您也可以使用循环来获取输入,而不是使用System.out.print

答案 3 :(得分:0)

尽可能初始化highTemp和lowTemp,并在必要时更新它们的值。

使用if关键字。