Reputation: 11
I have to find the lowest number in an array. It works when I manually make an array, but when I use a scanner to get numbers from the user and they put in a negative number, it does not consider the negative sign and acts as if the number is a positive number. Is there something scan.nextInt does to negative numbers that causes this?
System.out.println("Enter an array size.");
size = scan.nextInt();
int[] numbers = new int[size];
System.out.println("Enter each integer in the array and press Enter after each one.");
for(int i = 0; i < size; i++)
{
numbers[i] = scan.nextInt();
}
for(int j = 0; j < size; j++)
{
smallest = numbers[0];
if (numbers[j] < smallest)
{
smallest = numbers[j];
}
}
System.out.println("Smallest Number is " + smallest);
This is the code for reference
Upvotes: 0
Views: 1627
Reputation: 11622
You have to initialize your smallest out of the loop, preferably at the beginning. And if you are going to find the smallest, assign it a big value (if largest, assign a very small value);
int smallest = Integer.MAX_VALUE;
Integer.MAX_VALUE is the greatest possible value that you can assign to an integer in Java.
And always remember to release the resources. You have to close the scanner object when you're done with it.
scan.close(); // always release resources
Here is the demo code;
import java.util.Scanner;
public class FindLowest {
public static void main(String[] args) {
// initialization of variables
int size;
Scanner scan = new Scanner(System.in);
int smallest = Integer.MAX_VALUE;
System.out.println("Enter an array size.");
size = scan.nextInt();
int[] numbers = new int[size];
System.out.println("Enter each integer in the array and press Enter after each one.");
for (int i = 0; i < size; i++) {
numbers[i] = scan.nextInt();
}
scan.close(); // always release resources
for (int j = 0; j < size; j++) {
// smallest = numbers[0]; // dont initialize here, initialize at beginning
if (numbers[j] < smallest) {
smallest = numbers[j];
}
}
System.out.println("Smallest Number is " + smallest);
}
}
Enter an array size.
5
Enter each integer in the array and press Enter after each one.
1
-2
3
-4
5
Smallest Number is -4
Upvotes: 0
Reputation: 44854
You reset the smallest
variable every loop.
Try initializing it before the loop.
smallest = numbers[0];
for(int j = 0; j < size; j++)
{
if (numbers[j] < smallest)
{
smallest = numbers[j];
}
}
Upvotes: 3