Java - finding largest and smallest numbers using an array

I have to make a program that takes 10 numbers from user input, finds the largest and smallest number, and displays all inputs from the user. This program uses an array. Here is my code:

import java.util.Scanner; // program uses Scanner
public class ArrayTester {
    // begin execution
    public static void main(String[] args) {
        // declare and create array object
        // declare smallest and largest int variables 
        int[] numbers;
        numbers = new int[10];
        int smallest = numbers[0], largest = numbers[0];

        // create Scanner object
        Scanner input = new Scanner(System.in);

        // prompt user 
        System.out.print("Please enter 10 numbers: \n");
        // use for loop to obtain user input
        for (int counter = 0; counter < numbers.length; counter++) {
            numbers[counter] = input.nextInt();
        } // end obtaining input

        // enhanced for loop to find largest and smallest values
        for (int i : numbers) {
            if (numbers[i] < smallest) {
                smallest = numbers[i];
            } // end finding smallest
            else if (numbers[i] > largest) {
                largest = numbers[i];
            } // end finding largest number 
        } // end finding largest and smallest values

        // for loop to print user input 
        System.out.printf("%s%8s\n", "Index", "Input");
        for (int counter = 0; counter <= numbers.length; counter++) {
            System.out.printf("%5d%8d\n", counter, numbers[counter]);
        } // end printing input values

        // print smallest and largest numbers
        System.out.printf("Smallest number: %d\nLargest number: %d\n", smallest, largest);
        System.out.print("Programmed by Christian Lapinig");
    } // end main
 } // end ArrayTester

      

At this point, I can get user inputs, but I ran into this problem:

Please enter 10 numbers: 
454
392
33
41
6
44
39
21
12
2
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 454
at ArrayTester.main(ArrayTester.java:32)

      

Do I need a try and catch block to fix this?

+3


source to share


9 replies


A will try-catch

just swallow the exception. Your problem is that the extended for loop is iterating over the values โ€‹โ€‹of the array, but you are treating it as an index, so you check numbers[454]

and blow up right away because you are outside the array.

Iterating over indices or just working with values:



for (int i : numbers) {
    if (i < smallest) {
        smallest = i;
    } // end finding smallest
    else if (i > largest) {
        largest = i;
    } // end finding largest number 
} // end finding largest and smallest values

      

+1


source


for (int counter = 0; counter <= numbers.length; counter++) 

      



You put =<

, you must put instead <

. if the counter is equal to length, it tries to go out of range because the indices start at zero.

+1


source


Your problem has to do with the way you are using the for-loop, as already stated in other answers. However, a shorter approach in Java 8 would use a stream:

IntStream.of(numbers).max()

and IntStream.of(numbers).min()

+1


source


CHange

for (int i : numbers) {

      

to

for (int i=0;i<numbers.length;i++) {

      

0


source


Your problem is this loop:

for (int i : numbers) {

      

This loop means iterating over the elements of the array, not its indices. So you can say:

for (int a : numbers) {
   if(a > ...) {
   ....
}

      

Alternatively, you can use the array index as shown below:

for (int i = 0; i < numbers.lenth; i++) {
   if(numbers[i] > ...) {
   .....
}

      

0


source


Change it to:

for (int i=0 ;i< numbers.length; i++) {
            if (numbers[i] < smallest) {
                smallest = numbers[i];
            } // end finding smallest
            else if (numbers[i] > largest) {
                largest = numbers[i];
            } // end finding largest number 
        }

      

And <= to <

for (int counter = 0; counter < numbers.length; counter++) {
            System.out.printf("%5d%8d\n", counter, numbers[counter]);
        } 

      

Try a catch block just to handle your error in a graceful way. This will not solve your problem.

0


source


In java 8, you can get IntStream

and get summary statistics .

final IntSummaryStatistics stats = IntStream.of(numbers).summaryStatistics();

      

0


source


As many people have pointed out, you are using the values โ€‹โ€‹of your for-each loop and index, which means your code tries to access the position of whatever number your user enters into your array.

So, to fix this, you just need to do

smallest = i;

      

and

largest = i;

      

0


source


Try the code below,

import java.util.Scanner;

public class LargestSmallest
{
   public static void main(String[] args)
   {
      // assigning array of 10 numbers to numerals

      int a;
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter number of elements to find largest and smallest number: ");
      a = sc.nextInt();
      int numerals[] = new int[a];
      System.out.println("Enter " + a + " integers.");

      for(int b = 0;b < a;b++)
         numerals[b] = sc.nextInt();

      // assigning first numeral of an array to largest and smallest

      int largest = numerals[0];
      int smallest = numerals[0];

      for(int x = 1;x < numerals.length;x++)
      {
         if(numerals[x] > largest)
            largest = numerals[x];
         else if(numerals[x] < smallest)
            smallest = numerals[x];
      }
      System.out.println("Largest Number is: " + largest);
      System.out.println("Smallest Number is: " + smallest);
   }
}

      

For more information on finding the largest and smallest numbers using an array, click here .

0


source







All Articles