문제

I cant seem to figure it out. I need to ask the user for 3 floats, got it. Having trouble with the output of the high and low part. Any help would be awesome!

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();

    }

 }
도움이 되었습니까?

해결책

Here is a tip for you.

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

In this approach, there is no need to use if, switch, array or to sort.

다른 팁

I would use an array, and Arrays.sort(float[]) like so

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]);
}

Using Collections to 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));

You can also use a loop to get your input instead of using System.out.print

Initialize highTemp and lowTemp whenever you can and update their values when necessary.

Use the if keyword.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top