invalid value user input ask again to place into array - java

Scanner scanner = new Scanner(System.in);
int grade[] = new int[3];
for (int i = 0; i < grade.length; i++) {
System.out.println("Enter your test score:");
grade[i] = scanner.nextInt();
}
I've been trying to figure out how to make it so if the user input is below 0 or above 100 it will ask again. I'm very new to Java and this is the first language I'm learning. I would appreciate any pointers. Do I need to use a do-while loop instead of a for loop for this? Or do I implement an if statement into the for loop?

You can validate the input by putting an if block inside the for loop.
However, since your loop will only execute three times, you should change your increment condition only when user enters correct input or else not.
You also can use while loop here.
Here is some example code:
for (int i = 0; i < grade.length; i++)
{
System.out.println("Enter your test score:");
if(grade[i] < 0 || grade > 100)
{
i--;
continue;
}
grade[i] = scanner.nextInt();
}
The if block will check that if the input is outside boundaries, decrement i and restart the loop.

What I suggest is, instead of incrementing i in loop, you can increase the value in if condition. Like below,
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int grade[] = new int[3];
for (int i = 0; i < grade.length;) {
System.out.println("Enter your test score:");
int temp = scanner.nextInt();
if (temp >= 0 && temp <= 100) {
grade[i] = temp;
i++;
}else {
System.out.println("Please enter valid score");
}
}
scanner.close();
}
This basically gets a input value from user, if the value is greater or equal to 0 && lesser or equal to 100,then adds it to the Array and increments the loop count(array index value we can call it), else, prints message asking for valid input.

Instead of shoving the validation logic somewhere within the loop, you could also write a small utility method which neatly asks for valid input, and continues to do so until the user finally inputs something valid:
int promptInt(Scanner scanner, int min, int max, String errorMessage) {
while (true) {
int input = scanner.nextInt();
if (min <= input && input <= max) {
return input;
}
else {
System.out.println(errorMessage);
}
}
}
You could then simplify the loop:
int grade[] = new int[3];
for (int i = 0; i < grade.length; i++) {
System.out.println("Enter your test score:");
grade[i] = promptInt(0, 100, "Please enter a valid number");
}

Related

Java loop ignoring first input each loop

I am a beginner and have a simple piece of code that works - it is designed to ask a user for seven numbers and store them in an array then print out what they entered
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int[] inputs = new int[7];
System.out.println("Enter 6 numbers and a bonus ball");
for (int i = 0; i < 7; i++) {
inputs[i] = in .nextInt();
}
System.out.println("You have entered the numbers:");
for (int i: inputs) {
System.out.println(i);
}
}
What I want to do is add an error trap to make sure the number is not greater than 49 - I have added the following code and there are no errors and it runs fine but I have to add two numbers for each loop as it only stores the second input - can anyone help tell me why?
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int[] inputs = new int[7];
System.out.println("Enter 6 numbers and a bonus ball");
for (int i = 0; i < 7; i++) {
if ( in .nextInt() > 49) {
System.out.println("please enter a number less than 49");
inputs[i] = in .nextInt();
} else
inputs[i] = in .nextInt();
}
System.out.println("You have entered the numbers:");
for (int i: inputs) {
System.out.println(i);
}
}
when you do in.nextInt() it give you the "next" integer in the input, so you are doing this twice for each loop cycle, once in the if statement and the other in the if or else body. so you need invoke that function only once. something like this:
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int [] inputs = new int [7];
System.out.println("Enter 6 numbers and a bonus ball");
for (int i = 0; i < 7; i++)
{
int current_input = in.nextInt()
if ( current_input > 49)
{
System.out.println("please enter a number less than 49");
inputs [i] = in.nextInt();
}
else
inputs [i] = current_input;
}
System.out.println("You have entered the numbers:");
for (int i : inputs)
{
System.out.println(i);
}
}
I don't test the code but you have the idea.
here you have another problem still, and is that when the user types a number over 49, the second time you ask the number to the user, you don't test again that it's below 49 so the user can enter any number.

Validate multiple inputs to an array in java

I have a HOMEWORK assignment that involves users inputs.
I want to ask the user for three integer inputs in the range 1-7 and store them in an array.
What I have so far seems to validate properly if all inputs are over 7 and rules out strings etc inputs and but still allows for a single input to be over 7.
Any help is appreciated.
Scanner in = new Scanner(System.in);
boolean valid = false;
int[] inputRange = new int[3];
while(!valid)
{
System.out.println("enter three numbers: ");
if(in.hasNextInt())
{
for(int i = 0; i< inputRange.length; i++)
{
inputRange[i] = in.nextInt();
if(inputRange[i] >= 1 && inputRange[i] <= 9){
valid = true;
}
}
}else{
in.next();
}
}
Your logic is fine, but you need to restart valid to false again each time user is going to enter a new digit.
Here's how you can validate user input to be between 1-9 with a do-while using your same logic just a little bit different.
Also next time be sure to post a valid MCVE and not just "snippets" (it should include a main method and imports)
import java.util.Scanner;
public class ValidationOfNumbers {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
boolean valid = false;
int[] inputRange = new int[3];
int counter = 0;
int number = 0;
System.out.println("Enter 3 digits between 1-9"); //Ask for digits, numbers can have multiple digits, while digits are numbers from 0-9
for (int i = 0; i < inputRange.length; i++) {
valid = false; //Restart "valid" variable for each new user input
do {
number = in.nextInt();
if (number >= 1 && number <= 9) {
valid = true; //If valid, it will exit do-while
} else {
System.out.println("Enter a valid digit between 1-9");
}
} while (!valid);
inputRange[i] = number; //We know it's valid because it went out of do-while, so we can now store it in the array
}
for (int i = 0; i < inputRange.length; i++) {
System.out.println(inputRange[i]);
}
}
}
Here is the code
Scanner in = new Scanner(System.in);
int count = 0;
int data[] = new int[3];
while(count < 3) {
if(in.hasNextInt()) {
int val = in.nextInt();
if(val>=1 && val <=7) {
data[count] = val;
count++;
}
}
else {
in.next();
}
}

How to check if an int contains a letter

I am trying to validate my code by error checking. I want to make sure the integer people enter does not contain a letter or more.
Here is my code. I am supposed to solve this problem using a one dimensional array. I got the code working but I am having problems with adding the error checking in.
Any help would be appreciated. Thanks
public void getNumbers() {
Scanner keyboard = new Scanner(System.in);
int array[] = new int[5];
int count = 0;
int entered = 0;
int k = -1;
while (entered < array.length) {
System.out.print("Enter a number ");
int number = keyboard.nextInt();
if (10 <= number && number <= 100) {
boolean containsNumber = false;
entered++;
for (int i = 0; i < count; i++) {
if (number == array[i]) // i Or j
{
containsNumber = true;
}
}
if (!containsNumber) {
array[count] = number;
count++;
} else {
System.out.println(number + " has already been entered");
}
} else {
System.out.println("number must be between 10 and 100");
}
//what does %d do?
for (int j = 0; j < count; j++) {
System.out.printf("%d ", array[j]);
}
System.out.println();
}
}
}
I'm assuming that you would want your program to ask the user to re-enter a number if they do not input a number the first time. In this scenario you might want to try something along the lines of this:
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number: ");
while(!sc.hasNextInt()) {
//print some error statement
sc.nextLine();
}
int number = sc.nextInt();
System.out.println("Number is: " + number); // to show the value of number
// continue using number however you wish
Since hasNextInt() returns a boolean determining whether or not the input is an Integer, the program will never leave the while-loop until the program can confirm that the user has entered an integer.
keyboard.nextInt() will throw a InputMismatchException if you input a String.
If you want to check whether Scanner has an integer to read, you can use keyboard.hasNextInt().
Alternatively, you can read the input as
String s = keyboard.next() which will take the input as a String, and then use s.matches(".*\\d+.*") to detect whether or not it is an integer.
UPDATE: To answer questions -
keyboard.hasNextInt() will return a boolean. So for example, after System.out.print("Enter a number"), you could have an if statement checking to see if keyboard can receive numerical input, ie. if(keyboard.hasNextInt). If this is true, that means the user has entered numerical input, and you could continue with sayingint number = keyboard.nextInt(). If it is false, you would know that the user input is non-numerical.

Java - No Duplicate number array

I am in the process of creating of a Lottery Program using Java via BlueJ and I am having trouble with the user inputted numbers and the number being generated by the program (up to and including 1-49), I need the numbers that are entered by the user to not be duplicate i.e. the user cannot enter 1 and 1.
I am not really sure how to get the numbers to not be duplicate i was thinking of using an Array but im not sure what type or where to begin im rather new to the whole programming thing.
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class JavaApplication8 {
public static void main(String[] args) {
Scanner user_input = new Scanner (System.in);
Scanner keyIn = new Scanner(System.in);
int[] LotteryNumbers = new int[6];
int input;
int count = 0;
System.out.print("Welcome to my lottery program which takes\nyour lottery numbers and compares\nthem to this weeks lottery numbers!");
System.out.print("\n\nPress the enter key to continue");
keyIn.nextLine();
for (int i = 0; i < LotteryNumbers.length; i++)
{
count ++;
System.out.println("Enter your five Lottery Numbers now " + count + " (must be between 1 and 49): ");
input = Integer.parseInt(user_input.next());
if (input < 1 || input > 49)
{
while (input < 1 || input > 49)
{
System.out.println("Invalid number entered! \nPlease enter lottery number (between 1 and 49) " + count);
input = Integer.parseInt(user_input.next());
if (input >= 1 || input <= 49)
{
LotteryNumbers[i] = input;
}
}
}
else
{
LotteryNumbers[i] = input;
}
}
System.out.println("Thank you for your numbers.\nThe system will now check if you have any matching numbers");
System.out.print("Press the enter key to continue");
keyIn.nextLine();
Random randNumGenerator = new Random();
StringBuilder output = new StringBuilder();
int[] ActLotteryNumbers = new int[6];
for (int j = 0; j < ActLotteryNumbers.length; j++)
{
int roll = randNumGenerator.nextInt(49);
ActLotteryNumbers[j] = roll;
}
System.out.println(Arrays.toString(ActLotteryNumbers));
int counter = 0;
for (int i = 0; i < LotteryNumbers.length; i++)
{
for (int j = 0; j < ActLotteryNumbers.length; j++)
{
if (LotteryNumbers[i] == ActLotteryNumbers [j])
{
counter ++;
System.out.println("The numbers that match up are: \n" + LotteryNumbers[i]);
}
}
}
if (counter == 0)
{
System.out.println("You had no matching numbers this week ... Try Again next week!");
}
}
}
As "fge" mentioned, use Set to add all the values that you are getting from the user.
Get the user inputs and add it to Set.
Use a Iterator to check the user entered values and generated random numbers.
Set myset = new HashSet();
myset.add(user_input1);
myset.add(user_input1);
To retrive use the iterator'
Iterator iterator = myset.iterator();
while(iterator.hasNext(){
int value= iterator.next();
if(randomValue==value)
//do your logic here
}
I am assuming this is for a school project/lab? (This is due to the JavaApplication8 class name) If that is the case, what the instructor is most likely looking for is a contains method.
For a contains method you write a method that takes an integer and checks to see if it is already in your LotteryNumbers array and returns a boolean. It would return true if it is in the array, false if it is not in it. This method would be called before inserting the number into LotteryNumbers. You could use your count variable that doesn't appear to be used anywhere else as the limit on your loop in the contains method to avoid checking uninitialized entries.
If there is no restriction on type, the set idea suggested by others works and is more efficient, it just depends on what you are supposed to be using for your requirements.
Additionally, the logic you use should most likely be applied to ActLotteryNumbers as well. If you can't have duplicates incoming, you shouldn't have duplicate values in the comparing array. Lottery isn't fair in real life, but not that unfair ;-)
First step should be checking your restrictions on this project.

Multiple Scanner Input In For Loop

I've just begun to learn how to program with Java and I had a question with regard to the scanner input. I'm building a little program that simply asks the user for input to create a numerical array. I was wondering if there was a way to check for the numerical input encompassing the for loop, instead of putting a while check on each of my cases in the for loop.
As well, any other comments or suggestions on my code to help me improve and understand what I am doing would be greatly appreciated!
Thank you!
Edit: I'm calling this class from a 'Main' class where I run the program.
import java.util.Scanner; //Import the use of the Java Scanner
public class ArrayBuild { // Open Application
private static Scanner input;
public Double[] anArray;
public static int arrayCount = 0;
public ArrayBuild() { // Constructor for ArrayBuild object
input = new Scanner(System.in);
arrayCount++;
System.out.println("This will be Array: " + arrayCount);
// Array Size Declaration
System.out.println("Enter Array Size: ");
while (!input.hasNextInt()) {
System.out.println("Please enter an integer for Array size!");
input.next();
}
int n = input.nextInt();
anArray = new Double[n]; // Create 'anArray' of size n
//
for (int i = 0; i < n; i++) { // Begin For Loop
if (i == 0) {
System.out.println("Enter First Number: ");
while (!input.hasNextDouble()) {
System.out.println("Please enter a number for array data!");
input.next();
}
Double D = input.nextDouble();
anArray[i] = D;
}
else if (i > 0 && i < (n - 1)) {
System.out.println("Enter Next Number: \n");
while (!input.hasNextDouble()) {
System.out.println("Please enter a number for array data!");
input.next();
}
Double D = input.nextDouble();
anArray[i] = D;
}
else if (i == (n - 1)) {
System.out.println("Enter Final Number: ");
while (!input.hasNextDouble()) {
System.out.println("Please enter a number for array data!");
input.next();
}
Double D = input.nextDouble();
anArray[i] = D;
}
} // End For Loop
}
} // Close Class
One thing you can do to simplify and write clean code is to always separate the repeating code. In your case, inside the for loop, you are only changing the print statement inside the if condition. Take the other code outside like this--
for (int i = 0; i < n; i++) { // Begin For Loop
if (i == 0)
System.out.println("Enter First Number: ");
else if (i > 0 && i < (n - 1))
System.out.println("Enter Next Number: \n");
else if (i == (n - 1))
System.out.println("Enter Final Number: ");
while (!input.hasNextDouble()) {
System.out.println("Please enter a number for array data!");
input.next();
}
Double D = input.nextDouble();
anArray[i] = D;
} // End For Loop

Categories