Reputation: 23
So this is my code so far, the user can input values and store them in an array. However what im trying to make is that the user input be between the range 1 and 50, if its outside of this range then i want some error message to print stating the range isnt between 1 and 50, and if the value is outside of the range, i want the loop to repeat until the user fills the array within the range 1 and 50. How should i go along to get these things done ?
import java.util.Scanner;
public class Input {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Please input a positive number between 1 and 50: ");
int userNumb = input.nextInt();
int[] array = new int[10];
do {
int i = 0;
array[i] = input.nextInt();
} while (userNumb < 0 || userNumb > 50);
System.out.println("The inputed values are: ");
for (int element : array) {
System.out.println(element + ",");
}
}
}
Upvotes: 1
Views: 688
Reputation: 6920
There are a few flaws in your code. First of all, you need a loop that makes sure that the n (array.length
) elements have been inserted and inside that loop add your controls (inputted a proper number and number included between 1 and 50).
The i
variable should be declared outside the loop to help you in keeping track of how many correct numbers have been inserted. Then, within your loop you could add your verifications.
public class Main {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
int[] array = new int[10];
int i = 0, temp;
do {
System.out.print("Please input a positive number between 1 and 50: ");
//Making sure that the user is entering a number
if (!input.hasNextInt()) {
System.out.println("Error! Please input a number between 1 and 50");
input.nextLine(); //getting rid of the wrong user input
continue; //jumping to the condition to repeat the cycle and skip the code working on a proper number
}
//Reading the number
temp = input.nextInt();
//Making sure the number is included in the range between 1 and 50
if (temp < 1 || temp > 50) {
System.out.println("Error! Please input a number between 1 and 50");
continue;
}
//Storing the value and incrementing the index for the i-th element
array[i] = temp;
i++;
} while (i < array.length);//Keep reading as long as the index hasn't covered all the elements
//Printing the array's content
System.out.println("The inputted values are: " + Arrays.toString(array));
}
}
On a side note, if it's not a constraint to display your elements with a loop, you could show the array's content with the toString()
method of the Arrays
class. This method yields a String
representation of the elements of the given array.
Upvotes: 1