Reputation: 13
I'm having trouble to ignore the negative numbers in finding the minimum of given numbers. here is my code to print the minimum number taking 10 inputs from the user in java. (I'm a fresher student and new in java. if you find any mistake then please help me to figure it out)
Scanner k = new Scanner (System.in);
int x, y, min;
System.out.println ("enter a number");
x = k.nextInt();
min = x;
for (int count=1; count < 10; count++) {
System.out.println ("enter a number");
y = k.nextInt;
if (y < min) {
min = y;
}
}
System.out.println (min);
That was my code to find the minimum number. But I want to find the minimum of all positive numbers. if the user enters negative number then I want to ignore that number.
Help me to make the code of finding the minimum number ignoring negative numbers.
Upvotes: 0
Views: 2288
Reputation: 442
if(y<min&&y>=0)
Is that what you mean?
private static Scanner k = new Scanner (System.in);
public static void main(String[] args) {
int min=getNumber(false);
for (int count=1; count<10; count++) {
int y=getNumber(true);
if(y<min&&y>=0)
min=y;
}
System.out.println(min);
}
private static int getNumber(boolean allowNegative) {
System.out.println("Please enter an integer:");
int n=0;
try {
n=Integer.parseInt(k.nextLine());
} catch(NumberFormatException nfe) {
System.err.println("Input must be an integer...");
return getNumber(allowNegative);
}
if(allowNegative) {
return n;
} else {
if(n<0) {
System.out.println("You cannot start with a negative number...");
return getNumber(allowNegative);
} else {
return n;
}
}
}
Upvotes: 2
Reputation: 42520
Check not only if the next number is smaller than your current minimum, but also if it is greater than (or equal) 0:
if (y<min && y >= 0){
instead of
if (y<min){
You also have to make sure the first number is not negative.
Upvotes: 2
Reputation: 380
Scanner k=new Scanner (System.in);
int x,y,min;
min=0;
for (int count=1;count<=10;count++){
System.out.println ("enter a number");
y=k.nextInt;
if (y<min && y>=0){
min=y;
}
}
System.out.println (min);
Made a few changes. This 1) Ensures only 10 inputs are taken 2) The value of min defaults to 0 if only negative numbers are entered. In your earlier code, if the first number was negative, min would still be set.
Upvotes: 0
Reputation: 11173
It's better if you store your all input number in an int
array. If I assume the array containing all number is - array[]
then look the code -
public class FindMinimumExceptNegative{
public static void main(String[] args){
int[] array = {-100, -4, 33, 45, 67, 2, -4, 56, 87, 234, 98, 24, 98, 56, 87, -10};
System.out.println("Minimum :" +findMinimumExceptNegative(array));
}
public static int findMinimumExceptNegative(int[] a){
int minimum = 0;
for(int i=0; i<a.length; i++){
if(a[i]>=0){
minimum = a[i];
break;
}
}
for(int i=1; i<a.length; i++){
if(minimum > a[i] && a[i]>=0){
minimum = a[i];
}
}
return minimum;
}
}
Upvotes: 0