2

I'm supposed to create an array of 7 integers called sevenInt. Ask user to input 7 integers between 80 and 120 and store each number into sevenInt. If user did not enter the right integer range, ask again until user get it right. Then, display those numbers in the sevenInt that are even numbers.

My code works to a certain extent.

1) If I key in the wrong integer range & then key in the correct integer range the second time round, my code does not work properly (i.e. the last number is printed as the first number, see bold in eg).

E.g. Enter 7 integers from 80-120: (system prompt)

79 80 81 82 83 84 85 (user input)

Please enter an integer between 80-120. (system prompt)

80 81 82 83 84 85 86 (user input)

80 82 84 80 (what is printed)

2) If the first integer I input is an odd number, what is printed won't be even.

E.g.

Enter 7 integers from 80-120: (system prompt)

101 103 104 107 109 110 111 (user input)

101 104 109 111 (what is printed)

Here's my code. Any idea how I should rectify the problem?

import java.util.Scanner;
    public class Exercise7 {

        public static void main(String[] args) {
            Scanner in = new Scanner(System.in);
            int[] sevenInt = new int[7];
            System.out.println("Enter "+sevenInt.length+" integers from 80-120: ");
            for(int i=0;i<sevenInt.length;i++)
            {
                int num = in.nextInt();
                if(num<80||num>120)
                {
                    System.out.println("Please enter an integer between 80-120.");
                    i--;
                }
                else
                {
                    sevenInt[i]=num;
                }
            }
            for(int i=0;i<sevenInt.length;i++)
            {
                if(i%2==0)
                {
                    System.out.print(sevenInt[i]+" ");
                }
            }
            System.exit(0);
        }
    }
}

1 Answer 1

2

The only mistake you make is if(i%2 == 0). It should be

if (sevenInt[i] % 2 == 0)

since you want to check the content to be even, not the index.


Sample:

Enter 7 integers from 80-120:
100
120
130
Please enter an integer between 80-120.
120
120
77
Please enter an integer between 80-120.
88
99
101
100 120 120 120 88

Sign up to request clarification or add additional context in comments.

2 Comments

why is it that the final output contains 3 120? is it because the program stores the number? How can I change the code such that after entering an integer between 80-120 upon prompt, the new 7 numbers are printed?
@bamboosymphony because I entered three 120s. Your new requirement is unclear. Do you want to only accept distinct integers or do you want to only print distinct ones? In both cases that is a new question and should be posted as one. This question is solved, please accept my answer by clicking on the checkmark on its top left.