简体   繁体   中英

How to check if array elements are the same

I'm trying to get 5 numbers by the users via console input and check if all elements of this arrays are the same. If so, it shall print "Kniffel!" (what's Yahtzee in Germany if you care to know). But I can't figure out how to check the actual input.

This is my code so far

public class Kniffel
{

    private static Scanner sc2;

    public static void main(String[] args) {

        int[] numbers = new int[5];

        System.out.println("Gib " + numbers.length + " Zahlen getrennt von Leerzeichen ein: ");

        sc2 = new Scanner(System.in);
        int i = sc2.nextInt();

        boolean flag = true;
        int first = numbers[0];

         for(int index = 1; index < numbers.length; index++){
                if (numbers[index] != first) flag = false;
            }
         if (flag) System.out.println("Kniffel!");


    }

}
for (int i=0; i<=numbers.length; i++) {
    numbers[i] = sc2.nextInt();
}

This will iterate over the array and assign a number provided by the user input to each index of the array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM