mercredi 30 septembre 2020

How to take values initiated in an if else statement to be used outside the statement?

hello I'm a newbie and I am having a hard time doing this program. I was wondering if there is any work around to get the value in the else statement be used outside the statement itself or any other way for this to work. The program is suppose to stop when there are 10 odd numbers in the array which i tried to do by putting it in a do while loop and assigning variable k to add 1 value if the the else statement detects an odd number but the value of k is only usable in the else statement.

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int num[] = new int[100];

        System.out.println("This program stops when 10 odd numbers are entered.");
        do {
            int j = 0;
            int k = 0;
            for (int i = 0; i <= num.length; i++) {
                System.out.println("Please enter element " + i);
                num[j] = sc.nextInt();

                if (j % 2 == 0)
                    System.out.println("Entered number is even");
                else
                    k = k + 1;
            }
        } while (k != 11);
    }
    
}

Aucun commentaire:

Enregistrer un commentaire