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 );
}
}
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.
您必须初始化minValue
,最好初始化minValue
高,例如Integer.MAX_VALUE
。
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);
}
You need to initialize minValue
to some highest value that user will not enter. For better safety, you should initialize to Integer.MAX_VALUE
.
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 );
}
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.
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());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.