Warm tip: This article is reproduced from stackoverflow.com, please click
arrays for-loop java methods

Array's methods and comands

发布于 2020-03-27 15:46:31

I was trying to obtain the minimun value and its index between an array of int.

I can't understand why if I use the for-loop inside the main method it doesn't work, but if I use the same code in an aux method it works. The code should be right.

The part of the code that is commented is the for-loop that doesn't work.

package minimoArray;
import java.util.Scanner;

public class minimoArray {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Inserisci 10 numeri interi: "); 
        int [] Arr = new int [10];
        //int a = Arr[0];
        int b = 0;

        for (int i = 0; i < Arr.length; i++) {    //NON si può riempire l'array con for-each
            Arr[i] = scanner.nextInt();         
        }

        /*
        for (int i = 0; i < Arr.length; i++) {      
            if (Arr[i] < a) {
                a = Arr[i];
                b = i;
            }
        }*/

        int minimo = minimo(Arr);

        for (int i = 0; i < Arr.length; i++) {  
            if (Arr[i] == minimo) {
                b = i;
            }
        }

        System.out.println(" il minimo è: " + minimo); 
        System.out.println(" l'indice del minimo è: " + b); 
    }

    private static int minimo (int [] a) {
        var min = a[0];
        for (int i = 1; i < a.length; i++) {
            if (a[i] < min ) {
                min = a[i];
            }
        }
        return min;
    }  
}
Questioner
Vitangelo Moscarda
Viewed
92
maio290 2020-01-31 17:20

Edit: Just saw that the a is commented out too, my mistake. However, here Nicktar's answer applies with the reason why, you set a to the first element of the array, whose numbers weren't even set yet. The solution stays the same though.

First of all, stick to the naming convention of Java. Classes start with an uppercase letter, variables start with a lowercase letter.

Your mistake in the for loop within your main method is that a isn't even definied there, therefore the whole loop shouldn't even compile.

Simply add the var a = Arr[0]; before the loop and start the loop at the index 1.