Java - No Duplicate number array - java

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.

Related

invalid value user input ask again to place into array

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");
}

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: Display the complete set of unique values input after the user enters each new value

I need to write a code that "Display the complete set of unique values input after the user enters each new value." Such as:
The·complete·set·of·unique·values·entered·is:↵
Unique·Value·1:·is·100↵
Unique·Value·2:·is·10↵
Unique·Value·3:·is·20↵
I have attached my code below, and have the code completed, however, it seems to come across errors on my very last line to produce the last "this is the first time (user input) has been entered" & the unique value portion results of Unique Value # is (user input that's unique and stored in array). There seems to be an error in the very last System.out.println("Unique...) line.
Any help would be greatly appreciated.
import java.util.Scanner;
import java.util.ArrayList;
public class DisplayUniqueValueInput {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// creating an ArrayList from user input
ArrayList<Integer> userInputs = new ArrayList<Integer>(5);
// prompt user and store input
int count = 0;
while (true) {
int a = 0;
while(true) {
System.out.print("Enter an integer between 10 and 100:");
a = Integer.parseInt(sc.nextLine());
if (a < 10 || a > 100)
System.out.println("Invalid input\n");
else
break;
}
count++;
if (count == 5)
break;
boolean ifExists = false;
for(int i = 0; i<userInputs.size(); i++) {
if (userInputs.get(i) == a) {
ifExists = true;
break;
}
}
if (!ifExists){
System.out.printf("This is the first time %d has been entered\n", a);
userInputs.add(a);
}
} // end while statement
// output unique values
System.out.println("\nThe complete set of unique values entered is:\n");
for(int i = 0; i < 5; i++) {
System.out.println("Unique Value" + userInputs[i] + "is:" + " ");
}
} // end main method
} // end of class
A little off-topic but if you must store unique elements, you normally go for a Set. That being said, in the portion of the code where you collect the user input, you are asking for 5 numbers but storing 4 e.g.:
int count = 0;
while (true) {
int a = 0;
while(true) {
System.out.print("Enter an integer between 10 and 100:");
a = Integer.parseInt(sc.nextLine());
if (a < 10 || a > 100)
System.out.println("Invalid input\n");
else
break;
}
// count++;
// if (count == 5) if you break here, the code below won't be reached
// break; thus you will never store the last user input
// Lists have a method contains that does exactly what you are trying to do
// Consider using ifExists = userInput.contains(a)
boolean ifExists = false;
for(int i = 0; i<userInputs.size(); i++) {
if (userInputs.get(i) == a) {
ifExists = true;
break;
}
}
if (!ifExists){
System.out.printf("This is the first time %d has been entered\n", a);
userInputs.add(a);
}
// consider breaking here after you have collected the last user input
// alternatively, use a do{ ... } while(); loop
count++;
if (count == 5)
break;
} // end while statement
You are not printing the iteration variable i e.g.:
// output unique values
System.out.println("\nThe complete set of unique values entered is:\n");
for(int i = 0; i < userInputs.size(); i++) {
System.out.println("Unique Value " + (i + 1) + ": is " + userInputs.get(i));
}
Also as mentioned in another answer, in your for-loop the variable i must go up to < userInputs.size() since if you try to go up to 5, it will break if the user entered duplicate values.
For the last loop, you should do this instead, because your array is to store unique numbers, right? So if there is less than 5 unique number, your program will break, and why don't use Set instead?
// output unique values
System.out.println("\nThe complete set of unique values entered is:\n");
for(int i = 0; i < userInputs.size(); i++) {
System.out.println("Unique Value" + userInputs.get(i) + "is:" + " ");
}
Your error is because in the last for loop you try to access your list with userInputs[i] instead of userInputs.get(i)
If you want to accept and print only unique value, Perhaps use Set instead of ArrayList. Example:-
public static void main(String args[]){
Set<Integer> numbers = new HashSet<>();
for(String input : args){
Integer num = Integer.parseInt(input);
if(!(numbers.add(num))){
throw new IllegalArgumentException("Number already have");
}
System.out.println("Unique number =" + num);
}
}
A Set is a collection that contains no duplicate elements. Refer to its javadoc for details.
** Sample above just for brevity, you may retrofit your program with Set type.

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.

Error checking duplicate user-input array values

I am self-learning Java and am stuck on a simple project. I'd like to receive 6 unique 'lottery' numbers from a user.
User will be asked to input an integer.
Each user input will be placed into an array.
If the user inputs a previously input number, I want to prompt to reenter the number again.
Recheck the new input. If unique, continue the for loop. If non-unique, run step 3 again.
So far, all I have is:
public static int[] userLottoInput()
{
int[] userNums = new int[6];
Scanner keyboard = new Scanner(System.in);
for (int i = 0; i < userNums.length; i++ ) {
System.out.printf("Enter Lottery number %d: ", i + 1);
userNums[i] = keyboard.nextInt();
for (int k=i; k<userNums.length; k++) {
while (k!=i && userNums[k] == userNums[i]) {
System.out.printf("if");
System.out.printf("Error! Try again: ");
userNums[i] = keyboard.nextInt();
}
}
}
}
Any help is appreciated!!
Try and keep you logic simple.
While the user hasn't enter 6 numbers, loop
Ask the user for a value
Check to see if it's a duplicate
If it is, ask the user to re-enter the value
If it's not (a duplicate) increment the counter to the next element...
For example...
public static int[] userLottoInput() {
int[] userNums = new int[6];
Scanner keyboard = new Scanner(System.in);
int i = 0;
// Keep looping until we fill the array, but
// allow the control to fall somewhere else
while (i < userNums.length) {
System.out.printf("Enter Lottery number %d: ", i + 1);
userNums[i] = keyboard.nextInt();
// Check for duplicates
boolean duplicate = false;
// We only need to check up to i - 1, as all the
// other values are defaulted to 0
// We also don't need to check for the last number entered ;)
for (int k = 0; k < i; k++) {
// Check for duplicated
if (userNums[k] == userNums[i]) {
System.out.println("No duplicates allowed, please try again");
duplicate = true;
// Break out of the loop as we don't need to check any more..
break;
}
}
// If no duplicates where found, update i to the next position
if (!duplicate) {
i++;
}
}
return userNums;
}
With this, there is only one point at which you prompt the user. Everything else is used to control the element position (i) to meet your requirements.
Now, I'm sure that there are other ways to do this and this is just a simple example ;)
Move the asking of number outside loop, when received the number loop over the numbers array to find a match. If match found re-ask for number (outside the for loop used for finding the match), else if match not found, then add the number to array.
Don't you think your for loop is little complicated. Anyways, you can try this :
for (int k=0; k<i-1; k++) { //Start k=0 means from the first stored value
while (k!=i && userNums[k] == userNums[i]) {
System.out.printf("if");
System.out.printf("Error! Try again: ");
userNums[i] = keyboard.nextInt();
}
}

Categories