using a loop get a user to input an integer 10 times then get the minimum

9.8k views Asked by At

I've got a homework assignment where I need to write a program using a loop that takes 10 integer values from a user and outputs the minimum of all values entered.

Here is what I've got:

import java.util.Scanner;

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

   int value;
   int minValue;

   Scanner scan = new Scanner(System.in);

   for( int i = 0; i < 10; i++ )
   {

      System.out.print( "Enter a number as an integer > " );   

      value = scan.nextInt( );

      if( value < minValue )

      minValue = value;

      }

      System.out.println( "The minimum number is " + minValue );


  }
 }
7

There are 7 answers

11
Naman Gala On BEST ANSWER

You have forgotten to initialize minValue.

Try this in your for loop

if (i == 0)
    minValue = value;

Or you can intialize before for loop like this

minValue = Interger.MAX_VALUE; //This is more efficient code.
0
badjr On

You have to initialize minValue, preferably to something high, like Integer.MAX_VALUE.

0
Elliott Frisch On

You have to give your minValue an initial value. I suggest Integer.MAX_VALUE. Also, you might use Math.min(int, int) like

public static void main(String[] args) {
    int minValue = Integer.MAX_VALUE;
    Scanner scan = new Scanner(System.in);
    for (int i = 0; i < 10; i++) {
        System.out.print("Enter a number as an integer > ");
        System.out.flush();
        minValue = Math.min(scan.nextInt(), minValue);
    }
    System.out.println("The minimum number is " + minValue);
}
0
brb tea On

You need to initialize minValue to some highest value that user will not enter. For better safety, you should initialize to Integer.MAX_VALUE.

0
StackFlowed On

You want to start with a correct value for minValaue.We should set it to MAX_VALUE

public static void main (String [] args )
{    
   int value;
   int minValue=Interger.MAX_VALUE;
   Scanner scan = new Scanner(System.in);
   for( int i = 0; i < 10; i++ )
   {
      System.out.print( "Enter a number as an integer > " );   
      value = scan.nextInt( );
      if( value < minValue ) {
          minValue = value;
      }
   }
   System.out.println( "The minimum number is " + minValue );
}
0
lightning_missile On
if( value < minValue )

your minValue is uninitialized because it's local. You are comparing value to nothing. If you want to get the default value of an int variable which is 0, make it a global variable. Otherwise, give it your own default value, perhaps Integer.MAX_VALUE as other answers suggested.

0
Shadow On

You forgot to initialize your minValue variable with a starting number. Best bet would be to initialize it with Integer.MAX_VALUE, like so:

int minValue = Integer.MAX_VALUE;

Also, you should change how you get your integer slightly, to something like:

value = Integer.parseInt(scan.nextLine());