1

I need to ensure that a user enters a number between 10 and 100. If they do not, I want them to enter a new number. In between the asterisks is where my problem is (I think). Thanks in advance.

import java.util.Scanner;

public class Duplicate 

{

  public static void main(String[] args)

  {

    Scanner input = new Scanner(System.in);

    int[] array = new int[5];

    System.out.println("Enter 5 integers between 10 and 100 (inclusive):");

    for (int i = 0; i < array.length; i++)   

    ****if ((input.nextInt() <= 100) || (input.nextInt() >= 10))

    {

      array[i] = input.nextInt();

    }

    ****else { System.out.print("Please enter a number greater than 9 and less than 101."); }

    for (int i = 0; i < array.length; i++)

      System.out.print(array[i] + ", ");

    System.out.println();

    System.out.println("Unique values are: ");

    for (int i = 0; i < array.length; i++) {

      boolean show = true;

      for (int j = 0; j < i; j++)

        if (array[j] == array[i]) {

          show = false;

          break;

        }

      if (show)

        System.out.print(array[i] + ", ");

    }

  }

}
1
  • Please learn how to indent your code. Failing to follow standard guidelines isn't clever. Commented Oct 9, 2011 at 0:40

1 Answer 1

2
if ((input.nextInt() <= 100) || (input.nextInt() >= 10))
  array[i] = input.nextInt();

You are calling nextInt three times which reads the next three integers. So if the user enters 5 then 150, then -1, this will be the same as

if (5 <= 100 || 150 >= 10)
  array[i] = -1;

which succeeds when it should not.

You are also using || (or) instead of && (and) so if the user entered 1 after the problem above is fixed, it would look like

if (1 <= 100 ||/* or */ 1 >= 10)
  array[i] = 1;

which succeeds because 1 <= 100.

Instead, just read one int and use &&.

int userEnteredInt = input.nextInt();
if (10 <= userEnteredInt && userEnteredInt <= 100)
  array[i] = userEnteredInt;
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I had a feeling the or statement might be an issue. I guess I also did not understand how nextInt() was being read. Thanks again.

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.