-1

I am a beginner programmer working on this exercise for an online class. I'm supposed to write a program that takes ten numbers from a user, finds the lowest number, and prints it back. I've viewed a few other similar questions, but couldn't find anything that worked for me. Here's what I have thus far, no errors or anything. I can't figure out why it gives me this:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
    at Exercise6_9.min(Exercise6_9.java:41)
    at Exercise6_9.main(Exercise6_9.java:31)

after entering 10 numbers. As a note, I have looked at this question, they are not the same. I wasn't quite asking what my error was and how to solve it, but rather why it's coming up in my example when my IDE shows no problems prior to running the program.

import java.util.Scanner;

public class Exercise6_9 {

    public static void main(String[] args) {

        double[] numbers = new double[10];
        Scanner input = new Scanner(System.in);
        System.out.println("Enter 10 numbers.");
        for (int i = 0; i < numbers.length; i++ ){
            numbers[i] = input.nextDouble();
        }
        min(numbers);
    }
    public static double min(double[] numbers){

        double min = numbers[10];
        for (int i=0;i<numbers.length;i++){
            if (numbers[i] < min){
                min = numbers[i];
                System.out.println(min);
            }
        }
        return min;
    }
}
  • make it `double min = numbers[0];` – dumbPotato21 May 25 '17 at 20:54
  • 1
    No errors is contradicted by you saying you're getting an exception, y'know. Question: are you permitted to use streams? – Makoto May 25 '17 at 20:54
  • @ChandlerBing After doing this, it no longer gives the error in the console, but it also doesn't print anything at all...any idea as to why? Thanks. – Tucker Campbell May 25 '17 at 20:56
  • @Makoto I'm not sure what you mean by streams, so I would assume no but I honestly have no idea. And what I meant by no errors is that in my IDE (Eclipse) it doesn't point out anything that would cause an error. – Tucker Campbell May 25 '17 at 20:57
  • `System.out.println(Arrays.stream(numbers).min().getAsDouble());` I think that's what Makoto meant ;) – Nir Alfasi May 25 '17 at 21:03

1 Answers1

5

The array index start from 0 , so you don't have an element numbers[10];, instead the 10th element is represented by :

double min = numbers[0];
//                   ^-------//this is the 1st element

double min = numbers[9];
//                   ^-------//this is the 10th element
Graham
  • 7,431
  • 18
  • 59
  • 84
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140