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] + ", ");
}
}
}
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;
精彩评论