Steve Steve - 7 months ago 10
Java Question

Novice java code about sorting numbers

This is the code i was working on in class. I would be asking my teacher but today is a sunday.

okay straight off the bat, I need to sort through some numbers and find the highest number and the lowest.

So what works and what doesn't?

The code finds the highest number under the variable of iMax. With the tweaking of a new variable name iMin, and a < (lesser sign) it should be giving me the lowest number found but it doesn't and that's the problem. Instead its telling me 0.0 and that is not one of the many random numbers i could choose. To put it plainly, the numbers 1000,2000,3000,4000,5000. it tells me 5000 is the highest number and 0.0 was the lowest. 0.0 was not one of my numbers and i have scratched my head for too long, please help me with this problem as it is driving me up the wall. So heres the code:
import java.util.Scanner;
public class JustWork {

public static void main(String[] args) {
double [] run1 = new double[7];
double iMax = run1[0];
double iMin = run1[0];

Scanner input = new Scanner(System.in);

for (int i = 0; i<run1.length; i++)
{
System.out.println("Score from Judge " + (i+1) + ": ");
run1[i] = input.nextDouble();
}

for (int i = 1; i<run1.length; i++)
{ if (run1[i]< iMin)
iMin = run1[i];
}

for (int i = 1; i<run1.length; i++)
{ if (run1[i]> iMax)
iMax = run1[i];
}


System.out.println("the minimum score is: " + iMin);

System.out.println("the maximum score is: " + iMax);
}


}

for example, if i put in the following numbers:3,4,5,6,7,8,9 System.out.prints out this:

Score from Judge 1:
3
Score from Judge 2:
4
Score from Judge 3:
5
Score from Judge 4:
6
Score from Judge 5:
7
Score from Judge 6:
8
Score from Judge 7:
9
the minimum score is: 0.0
the maximum score is: 9.0

Answer

When you initialize the double array, they are by default assigned 0s for each element.Then when you assign run1[0] to iMin and iMax, you have already set 0 as min implicitly. To avaoid that, just assign the initial values after getting the input

public static void main(String[] args) {
    double [] run1 = new double[7];
    Scanner input = new Scanner(System.in);

    for (int i = 0; i<run1.length; i++)
    {
        System.out.println("Score from Judge " + (i+1) + ": ");
        run1[i] = input.nextDouble();   
    }

    double iMax = run1[0];
    double iMin = run1[0];
    for (int i = 1; i<run1.length; i++)
    { if (run1[i]< iMin)
        iMin = run1[i];
    }

    for (int i = 1; i<run1.length; i++)
    { if (run1[i]> iMax)
        iMax = run1[i];
    }
    System.out.println("the minimum score is: " + iMin);
    System.out.println("the maximum score is: " + iMax);
}