Non duplicates numbers in user input - java

I am trying to work out how to create an input validation where it won't let you enter the same number twice as well as being inside a range of numbers and that nothing can be entered unless it's an integer. I am currently creating a lottery program and I am unsure how to do this. Any help would be much appreciated. My number range validation works but the other two validations do not. I attempted the non duplicate number validation and i'm unsure how to do the numbers only validation. Can someone show me how to structure this please.
This method is in my Player class
public void choose() {
int temp = 0;
for (int i = 0; i<6; i++) {
System.out.println("Enter enter a number between 1 & 59");
temp = keyboard.nextInt();
keyboard.nextLine();
while ((temp<1) || (temp>59)) {
System.out.println("You entered an invalid number, please enter a number between 1 and 59");
temp = keyboard.nextInt();
keyboard.nextLine();
}
if (i > 0) {
while(temp == numbers[i-1]) {
System.out.println("Please enter a different number as you have already entered this");
temp = keyboard.nextInt();
keyboard.nextLine();
}
}
numbers[i] = temp;
}
}

Do it as follows:
import java.util.Arrays;
import java.util.Scanner;
public class Main {
static int[] numbers = new int[6];
static Scanner keyboard = new Scanner(System.in);
public static void main(String args[]) {
// Test
choose();
System.out.println(Arrays.toString(numbers));
}
static void choose() {
int temp;
boolean valid;
for (int i = 0; i < 6; i++) {
// Check if the integer is in the range of 1 to 59
do {
valid = true;
System.out.print("Enter in an integer (from 1 to 59): ");
temp = keyboard.nextInt();
if (temp < 1 || temp > 59) {
System.out.println("Error: Invalid integer.");
valid = false;
}
for (int j = 0; j < i; j++) {
if (numbers[j] == temp) {
System.out.println("Please enter a different number as you have already entered this");
valid = false;
break;
}
}
numbers[i] = temp;
} while (!valid); // Loop back if the integer is not in the range of 1 to 100
}
}
}
A sample run:
Enter in an integer (from 1 to 59): 100
Error: Invalid integer.
Enter in an integer (from 1 to 59): -1
Error: Invalid integer.
Enter in an integer (from 1 to 59): 20
Enter in an integer (from 1 to 59): 0
Error: Invalid integer.
Enter in an integer (from 1 to 59): 4
Enter in an integer (from 1 to 59): 5
Enter in an integer (from 1 to 59): 20
Please enter a different number as you have already entered this
Enter in an integer (from 1 to 59): 25
Enter in an integer (from 1 to 59): 6
Enter in an integer (from 1 to 59): 23
[20, 4, 5, 25, 6, 23]

For testing a value is present in the numbers array use Arrays.asList(numbers).contains(temp)
May better if you use an ArrayList for storing numbers.

I would rewrite the method recursively to avoid multiple loops.
If you are not familiar with recursively methods it is basically a method that calls itself inside the method. By using clever parameters you can use a recursively method as a loop. For example
void loop(int index) {
if(index == 10) {
return; //End loop
}
System.out.println(index);
loop(index++);
}
by calling loop(1) the numbers 1 to 9 will be printed.
In your case the recursively method could look something like
public void choose(int nbrOfchoices, List<Integer> taken) {
if(nbrOfChoices < 0) {
return; //Terminate the recursively loop
}
System.out.println("Enter enter a number between 1 and 59");
try {
int temp = keyboard.nextInt(); //Scanner.nextInt throws InputMismatchException if the next token does not matches the Integer regular expression
} catch(InputMismatchException e) {
System.out.println("You need to enter an integer");
choose(nbrOfChoices, taken);
return;
}
if (value < 1 || value >= 59) { //Number not in interval
System.out.println("The number " + temp + " is not between 1 and 59.");
choose(nbrOfChoices, taken);
return;
}
if (taken.contains(temp)) { //Number already taken
System.out.println("The number " + temp + " has already been entered.");
choose(nbrOfChoices, taken);
return;
}
taken.add(temp);
choose(nbrOfChoices--, taken);
}
Now you start the recursively method by calling choose(yourNumberOfchoices, yourArrayList taken). You can also easily add two additonal parameters if you want to be able to change your number interval.

What you want to do is use recursion so you can ask them to provide input again. You can define choices instead of 6. You can define maxExclusive instead 59 (60 in this case). You can keep track of chosen as a Set of Integer values since Sets can only contain unique non-null values. At the end of each choose call we call choose again with 1 less choice remaining instead of a for loop. At the start of each method call, we check if choices is < 0, if so, we prevent execution.
public void choose(Scanner keyboard, int choices, int maxExclusive, Set<Integer> chosen) {
if (choices <= 0) {
return;
}
System.out.println("Enter enter a number between 1 & " + (maxExclusive - 1));
int value = keyboard.nextInt();
keyboard.nextLine();
if (value < 1 || value >= maxExclusive) {
System.out.println("You entered an invalid number.");
choose(keyboard, choices, maxExclusive, chosen);
return;
}
if (chosen.contains(value)) {
System.out.println("You already entered this number.");
choose(keyboard, choices, maxExclusive, chosen);
return;
}
chosen.add(value);
choose(keyboard, --choices, maxExclusive, chosen);
}
choose(new Scanner(System.in), 6, 60, new HashSet<>());

I hope it will help , upvote if yes
import java.util.ArrayList;
import java.util.Scanner;
public class Test {
private ArrayList<String> choose() {
Scanner scanner = new Scanner(System.in);
ArrayList<String> alreadyEntered = new ArrayList<>(6); // using six because your loop indicated me that you're taking six digits
for(int i = 0 ; i < 6 ; ++i){ // ++i is more efficient than i++
System.out.println("Enter a number between 1 & 59");
String digit;
digit = scanner.nextLine().trim();
if(digit.matches("[1-5][0-9]|[0-9]" && !alreadyEntered.contains(digit))// it checks if it is a number as well as if it is in range as well if it is not already entered, to understand this learn about regular expressions
alreadyEntered.add(digit);
else {
System.out.println("Invalid input, try again");
--i;
}
}
return alreadyEntered // return or do whatever with the numbers as i am using return type in method definition i am returning
}
scanner.close();
}
using arraylist of string just to make things easy otherwise i would have to to some parsing from integer to string and string to integer

Related

Bingo game Java

I'm trying to write a java code with(bingo game),(bullseye game)
the rules are simple:
computer picks 4 numbers
user input 4 numbers
must check the user input is between 1 to 10
If the user input exists in the computer randomized numbers it will be 1 bulls
If a number exist in the same location of the computer randomized number it will show 1 "eye"
Max limit is 20 tries until the user is considered "failed"; I need to print each round how many bulls were and how many eye were by the user input;
Example:
if the pc randomizing 1 4 6 7
and the user type 3 4 1 7
the output will be 3 bulls and 2 eyes.
my code prints 0 and 0 at the end.
Thanks for the help!
Here is my code:
import java.util.Random;
import java.util.Scanner;
public class ArraysEx1 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Random r = new Random();
int[] pcGuess = new int[4];
int[] playerGuess = new int[4];
int countGuess = 0, bulls = 0, eye = 0;
final int maxGuess = 20;
System.out.println("Please press enter to begin");
in.nextLine();
boolean areNumbersCorrect = true; // a boolean value to define if the user input are correct (values between 1 to 10)
for (; countGuess < maxGuess; countGuess++) {
System.out.println("Please enter 4 numbers between 1-10");
for (int i = 0; i < playerGuess.length; i++) {
playerGuess[i] = in.nextInt();
pcGuess[i] = r.nextInt(10)+1;
if (playerGuess[i] < 0 || playerGuess[i] > 10) { // an if statement to check if the user input are correct
areNumbersCorrect = false;
do { // do while loop if the boolean is not true. (force the user to enter correct values)
System.out.println("Please try again");
for (int j = 0; j < playerGuess.length; j++) {
playerGuess[j] = in.nextInt();
if (playerGuess[j] > 0 && playerGuess[j] < 10) {
areNumbersCorrect = true;
continue;
}
}
} while (!areNumbersCorrect); // end of do while loop
}
for (int j=pcGuess.length; j>0; j--) { // for loop to check each number from the user and computer.
if (playerGuess[i] == pcGuess[i]) {
eye++; // if the user number exist in the same location evaluate eye++
if (playerGuess[i]%pcGuess[j]== 0) {
bulls++; // if the user number exist in the randomized number but not in the same location evaluate bulls++
}
}
}
System.out.println(
eye+" Hits!(same pc number and location)"+" And: "+bulls+" Numbers exist");
} if(eye==4&&bulls==4) {
break;
}
}
System.out.println("It took you: "+countGuess+" Times to guess the numbers");
}
}
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
public class ArraysEx1 {
public static void main(String[] args) {
ArrayList<Integer> randNumbers = new ArrayList<>();
Random random = new Random();
String input;
int number;
Scanner sc = new Scanner(System.in);
do {
System.out.println("Please press enter to begin");
input = sc.nextLine();
}while (!input.equals(""));//loop while user doesn't press ENTER
for (int i = 0; i < 4; i++){
randNumbers.add(random.nextInt(10) + 1);//loop to fill the randNumbers arraylist with random numbers
}
/*
randNumbers.add(3);
randNumbers.add(2);
randNumbers.add(9);
randNumbers.add(9);
*/
System.out.println("My random numbers: " + randNumbers.toString());
int counter = 0;
int bulls = 0;
int eyes = 0;
do {
System.out.println("Please enter 4 numbers between 1-10");
number = sc.nextInt();
if (number > 0 && number <= 10){
//System.out.println("index of rand: " + randNumbers.indexOf(number));
//System.out.println("count: " + counter);
if (randNumbers.indexOf(number) == counter){
eyes++;
System.out.println("eyes++");
}else if (randNumbers.contains(number)){
bulls++;
System.out.println("bulls++");
}
counter++;
System.out.println("Number " + counter + " introduced. " + (4 - counter) + " more to go.");
}else {
System.out.println("Wrong number.");
}
}while (counter < 4);//loop for user to introduce valid numbers
System.out.println("You scored " + bulls + " bulls and " + eyes + " eyes.");
}
}
Try this piece of code. Note that I used ArrayList rather than an array, as it offers methods such as .contains() and .indexof().
WARNING: Code will fail if the randNumbers arraylist contains two numbers that are equals, such as the 3-2-9-9 array that is commented when you input 9-9-9-9 as your number guesses. This is because .indexof() method:
Returns the index of the first occurrence of the specified element
in this list, or -1 if this list does not contain the element.
Meaning the code fails to account the last 9 as it will compare the count index (3) to the first occurrence of 9 in the randNumbers, which is 2, making it false and not increasing eyes count.
Since I'm short on time, and this is an assigment you have and just copying it won't teach you much, I'll leave it to you to solve this specific case (I already told you what's wrong, won't be difficult to solve).

Java number guessing

a. declare a final int, and assign a value of 6 as the guessed number
// b. create a Scanner to get user input
// c. use a do {} while loop to prompt the user to enter an integer between 1 and 10,
// assign the user input to an int, and compare to the guessing number
do{
} while ();
// d. if the number matches the guessed number,
// print out a message that the number entered is correct.
I am stuck on the do while loop portion of the problem
import java.util.Scanner;
public class Number {
public static void main(String[] args) {
int value = 6;
int guess = 0;
int num = 0;
do {
System.out.println("Please enter a number between 1 and 10: ");
Scanner number = new Scanner(System.in);
guess = number.nextInt();
} while (num <= 10);
if (guess == value);
System.out.println("Congratulations you guessed the correct number!");
if (guess != value);
System.out.println("The number does not match.");
}
}
This is the result I am getting. I cannot figure out why it wont print the messages saying the number is correct or the number did not match.
Please enter a number between 1 and 10:
4
Please enter a number between 1 and 10:
5
Please enter a number between 1 and 10:
6
The semicolon after the if statement stops it from working and makes no sense
if (guess == value);
^ No no no
Should be
if (guess == value) {
System.out.println("Congratulations you guessed the correct number!");
}
Or
if (guess == value)
System.out.println("Congratulations you guessed the correct number!");
You should also increment num or the while makes no sense
Remove the Semicolon after the ifstatement, and i strongly advise you to use {} to wrap all your statements.
Morover you should increase num inside your while loop, and move the guessing part inside your while loop. so the correct messages are printed out in every loop.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int value = 6;
int guess = 0;
int num = 0;
do {
System.out.println("Please enter a number between 1 and 10: ");
Scanner number = new Scanner(System.in);
guess = number.nextInt();
num++;
if (guess == value) {
System.out.println("Congratulations you guessed the correct number!");
break;
}
if (guess != value) {
System.out.println("The number does not match.");
}
} while (num <= 10);
}
}
You code basically looks like this:
ask user for a number from 1 to 10
and do this forever
now check whether the number entered is the right guess
So as long as the user does what he is told, you keep asking and reasking. You never get to "now check...".
The loop needs to encompass the checking for the right guess, and needs to be terminated on the right guess.
(Edited) I slightly misread the original code, thinking that 'num' was the input value. Nope, the input number is called 'number'. I suggest the counter be renamed for clarity, maybe 'guessCount'. And of course remember to increment it with each guess.

Java - while loop for scanner validation results in failed input

I am trying to add the following scanner validation as follows;
public void promptFilmRating() {
while (!filmScanner.hasNextInt()) {
System.out.println("Please enter a number instead of text.");
filmScanner.next();
}
while (filmScanner.nextInt() > 5 || filmScanner.nextInt() < 1) {
System.out.println("Your number is outside of the rating boundaries, enter a number between 1 and 5.");
filmRatingOutOfFive = filmScanner.nextInt();
}
}
However when using the code that relates to the integer between value validation, repeated inputs are needed in order to record the original input and I am unsure on how to correct this, any advice would be fantastic.
I believe your problem is in while (filmScanner.nextInt() > 5 || filmScanner.nextInt() < 1) {.
Every call to filmScanner.nextInt() asks the stream for a new integer, so by calling .nextInt() twice in the while statement, you are asking for two numbers.
You might want to consider combining your two loops into one.
Example:
int myNum;
do {
myNumb = filmScanner.nextInt();
} while (myNum > 5 || myNum < 1);
Store the value that you are getting in a variable, and use that variable to perform the checks.
Here is an example:
private void promptFilmRating() {
Scanner filmScanner = new Scanner(System.in);
int filmRatingOutOfFive;
do{
System.out.println("Please enter your rating for the film:");
filmRatingOutOfFive = filmScanner.nextInt();
if(filmRatingOutOfFive > 5 || filmRatingOutOfFive < 1)
System.out.println("Your number is outside of the rating boundaries, enter a number between 1 and 5.");
}while(filmRatingOutOfFive > 5 || filmRatingOutOfFive < 1);
System.out.println("You rated this film: "+filmRatingOutOfFive+" out of 5");
}

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.

Limit input to only print a fibonacci sequence up to 16 places?

I am have a program which prints off the fibonacci sequence up to a given input. The user puts in a number and it prints out the sequence up to that many numbers.
ex: input = 4 prints 1 1 2 3
I want to limit the program to only allowing an input 1-16. The way I have it now will print the sequence an then prints the error message? Any suggestions? Thank you
public class FibonacciGenerator
{
private int fibonacci = 1;
public FibonacciGenerator()
{
}
public int Fibonacci(int number)
{
if(number == 1 || number == 2)
{
return 1;
}
else if (number > 16)
{
System.out.println("Error must select 1-16");
}
else
{
int fib1=1, fib2=1;
for(int count= 3; count < 17 && count <= number; count++)
{
fibonacci = fib1 + fib2;
fib1 = fib2;
fib2 = fibonacci;
}
}
return fibonacci;
}
}
Here is my main method:
import java.util.Scanner;
public class FibonacciPrinter
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter an integer 1-16: ");
int input = in.nextInt();
FibonacciGenerator newNumber = new FibonacciGenerator();
System.out.println("Fibonacci sequence up to " + input + " places.");
for(int fibCount = 1; fibCount <= input; fibCount++)
{
int sequence = newNumber.Fibonacci(fibCount);
System.out.print(sequence);
}
}
}
As a recommendation don't make your methods or variables start with capital letter, capital letter is used by convention for Classes only.
Also, you should validate input variable before passing it to your method.
I mean:
if (input > 16 || input < 1) {
System.out.println("Enter a number between 1-16");
}
else {
for(int fibCount = 1; fibCount <= input; fibCount++)
{
int sequence = newNumber.Fibonacci(fibCount);
System.out.print(sequence);
}
}
In your Fibonacci function, your first line should be an if statement to see if the number is greater than 16. If it is, then you can throw an error.
Below is what it should be:
public int Fibonacci(int number) {
if (number > 16 || number < 1) throw new IllegalArgumentException("Error. Must select 1-16.");
// Rest of the code
}
In your Fibonacci function, for number not equal to 1 and 2. The return statement return fibonacci; will always be called. That's why the error message is printed with the sequence.
To avoid this, you can use #Frakcool method to validate variable input before passing it to Fibonacci function. Alternatively, you may use do-while loop to do this (force the user to retry).
do{
System.out.print("Enter an integer 1-16: ");
input = in.nextInt();
if (input<1 || input>16)
System.out.println("Error. Must select within 1-16.");
}while(input<1 || input>FibonacciGenerator.upper_limit);
Some other suggestion:
Make your methods and variables name start with a lower case letter
To avoid repeat calculation (for-loop in Fibonacci method), use integer array to store the fibonacci values and pass integer array instead of integer (for small input number such as 16). Another way is to set two more global variables to store the last and second last calculated values.
Make upper limit (and/or lower limit) as a global variable for better maintenance
public static int upper_limit = 16;
and get it in other class as
FibonacciGenerator.upper_limit

Categories