Question

I am writing a program that takes in user input and churns out the minimum value. After 10 inputs the user can type in a negative number as the sentinel to exit the loop. The problem is this works but for some reason the loop takes the sentinel value as an array element aswell. Can anyone tell me whats wrong?

public class java {

   public static void main(String[] args) {
   {

      double[] a=new double[10];
      Scanner arr=new Scanner(System.in);

      System.out.println("Please enter values");

      int size = 0;

      int x = 0;

      while ( x >= 0 )
      {
         System.out.println("Enter next value");    
         x = arr.nextInt();

         a[size]=x;
         size++;                   
      }

      System.out.println( "Minimum Value" );

      System.out.println((min(a)));
   }
}

public static double min( double[] arr )
{
   double minimum= arr[0];
   for (int i=1; i<arr.length; i++)
   {
      if (arr[i] < minimum)
      {
         minimum= arr[i];
      }
   }

   return minimum;
}
Was it helpful?

Solution

while ( x >= 0 )
{
    System.out.println("Enter next value"); 
    x = arr.nextInt();

    if(x >= 0) //Add this if block
    {
        a[size]=x;
        size++;         
    }
}

Additionally, change this line:

double[] a=new double[10];

to

int[] a = new int[10];

Finally, when you create a primitive int (or double), even in an array, the default value is 0. So if you enter -999 as your first input, your array will look like this:

{0,0,0,0,0,0,0,0,0,0}

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top