1

I am having a logic error with this code. I need to get ten int inputs from the user and then print out any number bigger than 10. The only problem is that if the very last number in the array is bigger than 10 it will not print.

 public class Bigger10
    {
        public static void main(String[] args)
        {
            System.out.println("Please enter 10 integer numbers");

            int[] num = new int[10];
            int count = 0;
            int num1 = StdIn.readInt();

            while(count<9)
            {
                num[count] = num1;
                count++;
                num1 = StdIn.readInt();
            }

            for(int i = 0;i<count;i++)
            {
                if(num[i]>10)
                {
                    System.out.printf("%d ", num[i]);
                }    
            }
        }
    }
2
  • 3
    thats because you are only checking till 8th index i.e. till 9th element only Commented Apr 18, 2017 at 16:44
  • for(int i = 0;i<count;i++) change it to i<=count Commented Apr 18, 2017 at 16:45

3 Answers 3

4

Rely on the array to tell you how large it is instead of your constant 9.

The fix is simple: in your loop, iterate over its length instead.

while(count < num.length) {

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

1 Comment

When I do that I get an error: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10. This just means that it's bigger than the array size right?
1
        int num1 =0;

        while(count<=9)
        {
            num1 = StdIn.readInt();
            num[count] = num1;
            count++;

        }

count should be <=9, because you need to scan 10 values. If it is <9, then you are only scanning 9 values.

num1 = StdIn.readInt(); should be the first statement in the while loop. If you add it to the end, then you are scanning an extra number. That number is not added to the array because the loop condition becomes false i.e count becomes 10. So the last number is not printed because it is not added to array.

Comments

0

The issue in the code is with the termination condition of the loop. The loop is only executing 9 times even though you want to read 10 integers from the user. To fix this, you can modify the condition in the while loop as follows:

scss

while(count<10)

Additionally, you should also update the for loop to match the size of the num array, like this:

css

for(int i = 0;i<10;i++

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.