I am to enter 5 numbers, between 10 and 100. As each number is read, the program must display it only if it's not a duplicate of a number already read. I have to provide for the "worst case" in which all five numbers are different. I have use the smallest possible array to solve this problem and display the complete set of unique values input after the user enters each new value.
Problem I'm having is I don't know how to make it so that the number is between 10 and 100. Here's what I have so far. Thanks!
import java.util.Scanner; import java.util.Arrays;
public class IsDuplicate {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
int array[] = new int [5];
int size = 0;
int x;
for (int i = 0; i < 5; i ) {
System.out.print("Enter an integer between 10 and 100: ");
x = input.nextInt();
if(size == 0 || newNumber(array, size, x)) {
System.out.println("This is the first time " x " has been entered.");
array[size] = x;
size ;
}
}
System.out.println("The complete set of unique values entered is: ");
for (int i = 0; i<size; i ) {
System.out.println("Unique value" (i 1) ": is " array[i]);
}
}
private static boolean newNumber(int y[], int size, int x) {
for (int i = 0; i <size; i ) {
if (y[i] == x) {
return false;
}
}
return true;
}
}
CodePudding user response:
You can implement this quite easily. All you have to do is adjust your for loop taking the inputs, and add in a check for the value of x to see if it is !(x < 10) && !(x > 100)
.
If your program is supposed to ask for another number when an unacceptable value has been entered, then you will also need to subtract 1 from i
to ensure you still get 5 numbers total.
if(size == 0 || newNumber(array, size, x) ) {
if(!(x < 10) && !(x > 100))
{
System.out.println("This is the first time " x " has been entered.");
array[size] = x;
size ;
}
else
{
System.out.println("The number you entered is outside the range of acceptable values.");
i = i - 1;
}
}