I am working on this project from the Java Programming book by Joyce Farrell, and I am having an issue with the Randomly Generated number and the user's guesses not being checked correctly. For example the user has 3 guesses, lets say their first guess it 2 and the first randomly generated number is 2 the program will print out You lose. When the guess is actually correct. Please help me. I have added the details of the program plus what I have done so far.
Create a lottery game application. Generate three random numbers (see Appendix D for help in
doing so), each between 0 and 9. Allow the user to guess three numbers. Compare each of the
user's guesses to the three random numbers and display a message that includes the user's
guess, the randomly determined three-digit number, and the amount of money the user has
won as follows.
Matching Numbers Award($)
Any one matching 10
Two matching 100
Three matching, not in order 1000
Three matching, in exact order 1,000,000
No match 0
Make certain that your application accommodates repeating digits. For example, if a user
guesses 1, 2, and 3, and the randomly generated digits are 1, 1, and 1, do not give the user
credit for three correct guesses - just one. Save the file as Lottery.
My Source Code
// Filename: Lottery.java
// Written by: Andy A
// Written on: 14 January 2015
import java.util.Scanner;
import java.util.Random;
public class Lottery {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
Random ranNum = new Random();
// LIMIT Contains The Numbers From 0 - 9
// TIMES Contains The Number of Time ranNum Should Run
final int LIMIT = 9;
final int TIMES = 3;
// Users Guesses
int usersFirstGuess;
int usersSecondGuess;
int usersThirdGuess;
// Randomly Generated Numbers
final int GenFirst = ranNum.nextInt(LIMIT);
final int GenSecond = ranNum.nextInt(LIMIT);
final int GenThird = ranNum.nextInt(LIMIT);
// User is asked for 3 guesses
System.out.println("Please enter your first guess: ");
usersFirstGuess = userInput.nextInt();
System.out.println("Please enter your second guess: ");
usersSecondGuess = userInput.nextInt();
System.out.println("Please enter your third and final guess: ");
usersThirdGuess = userInput.nextInt();
// Winning Amounts
final double WinTen = 10;
final double WinHun = 100;
final double WinThund = 1000;
final double WinMillion = 1000000;
final int WinZero = 0;
// Shows the randomly generated numbers
for(int x = 0; x < TIMES; ++x)
System.out.print(ranNum.nextInt(LIMIT) + " ");
System.out.println();
// First Generated
if(GenFirst == usersFirstGuess ) {
System.out.println("You have won: $" + WinTen);
}
else if(GenSecond == usersSecondGuess) {
System.out.println("You have won: $" + WinTen);
}
else if(GenThird == usersThirdGuess) {
System.out.println("You have won: $" + WinTen);
}
}
}
You are printing newly generated numbers with ranNum.nextInt(LIMIT), however you are comparing the user input with the numbers stored in the GenXXX variables.
Solution: Print the variables instead.
System.out.println(GenFirst + " " + GenSecond + " " + GenThird);
If you still want to use a loop for printing you can store the numbers in an array.
// generate
final int[] generated = new int[TIMES];
for (int x = 0; x < TIMES; x++)
generated[x] = ranNum.nextInt(LIMIT);
// print
for (int x = 0; x < TIMES; x++)
System.out.print(generated[x] + " ");
This should do the trick.
// Filename: Lottery.java
// Written by: Andy A
// Written on: 14 January 2015
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.Random;
public class Lottery {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
Random ranNum = new Random();
// LIMIT Contains The Numbers From 0 - 9
// TIMES Contains The Number of Time ranNum Should Run
final int LIMIT = 9;
final int TIMES = 3;
// Users Guesses
int usersFirstGuess;
int usersSecondGuess;
int usersThirdGuess;
List<Integer> guesses = new ArrayList<>();
// Randomly Generated Numbers
final int GenFirst = ranNum.nextInt(LIMIT);
final int GenSecond = ranNum.nextInt(LIMIT);
final int GenThird = ranNum.nextInt(LIMIT);
// User is asked for 3 guesses
System.out.println("Please enter your first guess: ");
usersFirstGuess = userInput.nextInt();
guesses.add(usersFirstGuess);
System.out.println("Please enter your second guess: ");
usersSecondGuess = userInput.nextInt();
guesses.add(usersSecondGuess);
System.out.println("Please enter your third and final guess: ");
usersThirdGuess = userInput.nextInt();
guesses.add(usersThirdGuess);
// Winning Amounts
final double WinTen = 10;
final double WinHun = 100;
final double WinThund = 1000;
final double WinMillion = 1000000;
final int WinZero = 0;
// Shows the randomly generated numbers
System.out.println(GenFirst + " " + GenSecond + " " + GenThird);
List<Integer> lottery = new ArrayList<>();
lottery.add(GenFirst);
lottery.add(GenSecond);
lottery.add(GenThird);
if (guesses.equals(lottery)) {
System.out.println("You have won: $" + WinMillion);
} else {
int matchCount = 0;
for (Integer guessValue : guesses) {
if (lottery.contains(guessValue)) {
matchCount++;
lottery.remove(guessValue);
}
}
switch (matchCount) {
case 0:
System.out.println("You have won: $" + WinZero);
break;
case 1:
System.out.println("You have won: $" + WinTen);
break;
case 2:
System.out.println("You have won: $" + WinHun);
break;
case 3:
System.out.println("You have won: $" + WinThund);
break;
}
}
}
}
Exactly,
why are you printing
System.out.print(ranNum.nextInt(LIMIT) + " ");
when you should be just printing
System.out.print(GenThird + " ");
System.out.print(GenSecond + " ");
System.out.print(GenFirst + " ");
This is not the problem of the randomly generated numbers, but if your way of showing them to the user.
Before your if / else if statements, in the for-loop you are generating new random numbers. That means, the number compared to the users input (genFirst) can be 3, but the number shown to the user in the for loop is a new random number, for example 2.
To fix this problem, you should display the generated numbers like that:
for (int ranInt : new int[] { GenFirst, GenSecond, GenThird}) {
System.out.println(ranInt);
}
This piece of code creates an array of the generated numbers and loops through them printing them. Obviously, you can also print GenFirst, then print GenSecond and then print GenThird.
I hope this helps!
Maybe this will help!
import java.util.Scanner;
import java.util.Random;
public class Qellonumrat {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
Random rand=new Random();
int random_integer=(int) rand.nextInt(10);
System.out.println("Guess the number: ");
int number=sc.nextInt();
while(true){
if(number == random_integer){
random_integer++;
System.out.println("Congrats you won!!!");
break;
}
else{
System.out.println("Try again");
break;
}
}
}
}
Related
I am having a problem with my program. When I compile and run my program everything runs great until it's time to display the guesses back to the user. when that happens the last guess always gets displayed as 0.
My assignment is to develop a program that simulates the high-low game. For each execution of the program, the game will generate a random number in the inclusive range of 1 to 100. The user will have up to 10 chances to guess the value. The program will keep track of all the user’s guesses in an array. For each guess, the program will tell the user if his/her guess was too high or too low. If the user is successful, the program will stop asking for guesses, display the list of guesses, and show a congratulatory message stating how many guesses he/she took. If the user does not guess the correct answer within 10 tries, the program will display the list of guesses and show him/her the correct value with a message stating that he/she was not successful. Regardless of the outcome, the program will give the user a chance to run the program again with a new random number.
This is what I have so far:
import java.util.Random;
import java.util.Scanner;
/**
*
* #author jose
*/
public class Assignment7
{
/*
*/
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int number;
String again = "y";
while (again.equalsIgnoreCase("y"))
{
int[] guesses = new int[10];
int tries = 0;
number = GetRandomNumber(1, 100);
System.out.println(number); // delete before submitting
int userGuess = GetUserGuess(1,100);
while (userGuess != number && tries < guesses.length - 1 )
{
guesses[tries] = userGuess;
LowOrHigh(number, userGuess);
userGuess = GetUserGuess(1, 100);
tries++;
}
if (tries != 10)
{
userGuess = guesses[tries];
tries++;
System.out.println("Congratulations! You were able to guess the correct number");
}
else
{
System.out.println("Sorry! You were not able to guess the correct number");
}
if (tries == 10)
{
System.out.println("Your guesses were incorrect");
System.out.print("You guessed: ");
for ( int i = 0; i < 10 ; i++)
{
System.out.print(guesses[i] + ", ");
}
System.out.println("The random number generated was " + number);
}
else
{
System.out.println("Well done! You were able to guess the "
+ "correct number in under 10 tries");
System.out.print("You guessed: ");
for ( int i = 0; i < tries; i++)
{
System.out.print(guesses[i] + " ");
}
System.out.println("The random number generated was "
+ number + ", it only took you " + tries + " tries.");
}
System.out.println("");
System.out.print("Do you wish to try again with a different "
+ "number? (Enter y or n ): ");
again = input.next();
System.out.println("");
}
}
/*
METHOD 1
Description
A method that generates the random number to be guessed returns the
random number to main. Two parameters are the two numbers needed to generate
the random number (1 and 100 in this case).
*/
public static int GetRandomNumber (int rangeLow, int rangeHigh)
{
Random gen = new Random();
int number;
number = gen.nextInt(rangeHigh) + rangeLow;
return number;
}
/*
METHOD 2
This method tells the user if the guess is too low or too high. It will have
2 parameters one for the random number and the second is the user guess.
*/
public static void LowOrHigh (int number, int userGuess )
{
if (userGuess > number )
{
System.out.println("The value that you guessed is too high, "
+"Try guessing a lower number. ");
System.out.println("");
}
else if (userGuess < number )
{
System.out.println("The value that you guessed is too low, "
+"Try guessing a higher number. ");
System.out.println("");
}
}
/*
METHOD 3
This method will get the user guess. It has 2 parameters which will be the
valid range the user should guess between (in this case 1 and 100). It will
return the users guess as an integer. This method should validate that the
users guess is between the two parameters.
*/
public static int GetUserGuess(int rangeLow, int rangeHigh)
{
Scanner scan = new Scanner(System.in);
int userGuess;
System.out.print("Enter a number between " + rangeLow + " and " + rangeHigh + ": ");
userGuess = scan.nextInt();
while (userGuess > rangeHigh || userGuess < rangeLow)
{
System.out.println("The number given was not within the range, Try again ");
System.out.println("");
System.out.print("Enter a number between " + rangeLow + " and " + rangeHigh + ": ");
userGuess = scan.nextInt();
}
return userGuess;
}
}
I'm sorry if its obvious im still pretty new to programming.
Whenever you store a guess, you always store it in guesses[tries], and then immediately afterwards, you increment tries. Your while condition then checks if tries is less than guess.length - 1.
More generally, to program you need to know how to debug. Debugging is generally the act of following along with the code and checking what it actually does vs. what you wanted it to do. You can use a debugger for this, alternatively, you can add a boatload of System.out statements to follow along.
Do that, and you'll find the error in your logic. I've already given you quite a sizable hint in the first paragraph ;)
I'm coding an arithmetic game where the user is asked a series of addition questions. I want to however randomly assign an operator for each question so that the question could be either:
Question 1: num1 + num2 =
or
Question 2: num1 - num2 =
I have been using the Math.random() method to randomise num1 and num2 the last thing I am struggling on is randomly generating '+' and '-'.
Is it something to do with the ASCII values of these two characters and then I can randomly pick between them? Thanks for the help!
As a side note, I want to ask the user to 'press enter' to start the game, but i'm not sure how to do it. Currently I've got the user to enter 'y' to start. Any ideas? Thanks so much.
//prompt user to start the game
System.out.println();
System.out.print("Press y to Start the Game: ");
String start_program = keyboard.next();
if (start_program.equals("y")) {
heres my code so far:
public static void main(String[] args) {
//mental arithmetic game
System.out.println("You will be presented with 8 addition questions.");
System.out.println("After the first question, your answer to the previous question will be used\nas the first number in the next addition question.");
//set up input scanner
Scanner keyboard = new Scanner(System.in);
//declare constant variables
final int min_range = 1, max_range = 10, Max_Number_of_Questions = 8;
long start_time, end_time;
//generate 2 random numbers
int random_number1 = (int) ((Math.random() * max_range) + min_range);
int random_number2 = (int) ((Math.random() * max_range) + min_range);
//declare variables
int question_number = 1;
int guess;
//prompt user to start the game
System.out.println();
System.out.print("Press y to Start the Game: ");
String start_program = keyboard.next();
if (start_program.equals("y")) {
//start timer
start_time = System.currentTimeMillis();
//ask the question
System.out.print("Question " + question_number + ": What is " + random_number1 + " + " + random_number2 + "? ");
//take in user input
guess = keyboard.nextInt();
while (guess == (random_number1 + random_number2) && question_number < Max_Number_of_Questions) {
System.out.println("Correct");
++question_number;
//generate a new question
//generate 2 random numbers
random_number1 = guess;
random_number2 = (int) ((Math.random() * max_range) + min_range);
//ask the question again
System.out.print("Question " + question_number + ": What is " + random_number1 + " + " + random_number2 + "? ");
//take in user input
guess = keyboard.nextInt();
}
end_time = System.currentTimeMillis();
int time_taken = (int) (end_time - start_time);
if (guess != (random_number1 + random_number2))
System.out.println("Wrong");
else {
System.out.println();
System.out.println("Well Done! You answered all questions successfully in " + (time_taken / 1000) + " seconds.");
}
}
}
You can use Random#nextInt to pick a random int from 0 to array.length - 1 which you can use as the index of an array of operators.
import java.util.Random;
public class Main {
public static void main(String[] args) {
char[] operators = { '+', '-', '*', '/' };
// Pick a random operator
Random random = new Random();
char op = operators[random.nextInt(operators.length)];
System.out.println(op);
}
}
A sample run:
/
I think for the random - and + characters you could use boolean like so:
Random rd = new Random(); // creating Random object
if(rd.nextBoolean()) {
//Do something
} else {
//Do Something else
}
For the enter, i think this is a game that is played in the console of the ide? Because then you can use a Scanner to track when enter is being pressed.
This will help you i think:
Java using scanner enter key pressed
The thing with the "Enter 'y' to start the game" is totally superfluous, as evidenced by the fact that you obviously don't have sensible things to do when the user does not enter 'y'.
So, since this is a command line application, why would anyone start it and then not want to play the game? Just go ahead and ask the first question! If the user did start that program by accident somehow, there will be no harm whatsoever, it's not that you're going to overwrite important files, start missiles or something like that.
You could try something like this.
Random r = new Random();
int[] signs = { 1, -1 };
char[] charSigns = { '+', '-' };
int a = r.nextInt(20);
int b = r.nextInt(20);
int sign = r.nextInt(2);
System.out.printf("%s %s %s = ?%n", a, charSigns[sign], b);
// then later.
System.out.printf("The answer is " + (a + signs[sign] * b));
this is my first question in this community as you can see I'm a beginner and I have very little knowledge about java and coding in general. however, in my beginner practices, I came up with a little project challenge for myself. as you can see in the figure, the loop starts and it prints out the number that is given to it through the scanner. the problem with my attempt to this code is that it gives me the output value as soon as I press enter. what I want to do is an alternative of this code but I want the output values to be given after the whole loop is done all together.
figure
So, basically what I want is to make the program give me the input values together after the loop ends, instead of giving them separately after each number is put.
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
calc(); }
public static int calc (){
Scanner scan = new Scanner(System.in);
int count = 1;
int pass = 0;
int notpass = 0;
System.out.println("how many subjects do you have? ");
boolean check = scan.hasNextInt();
int maxless = scan.nextInt();
if (check){
while(count <= maxless ){
System.out.println("Enter grade number " + count);
int number = scan.nextInt();
System.out.println("grade number" + count + " is " + number);
if (number >= 50){
pass++;
}else{
notpass++;
}
count++;
}
System.out.println("number of passed subjects = " + pass);
System.out.println("number of failed subjects = " + notpass);
}else{
System.out.println("invalid value!");
} return pass;
}
}
I think what you want to do is create an array of int numbers.
It would be something like this:
import java.util.Scanner;
public class Application {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int maxless = 5;
int[] numbers = new int[maxless];
int count = 0, pass = 0, notPass = 0;
while(count < maxless){
System.out.println("Enter grade number " + (count + 1) + ":");
numbers[count] = scan.nextInt();
if(numbers[count] >= 50){
pass++;
}
else{
notPass++;
}
count++;
}
for(int i=0; i<maxless; i++){
System.out.println("Grade number " + (i + 1) + " is " + numbers[i]);
}
}
}
The output is the following:
Enter grade number 1:
90
Enter grade number 2:
76
Enter grade number 3:
54
Enter grade number 4:
67
Enter grade number 5:
43
Grade number 1 is 90
Grade number 2 is 76
Grade number 3 is 54
Grade number 4 is 67
Grade number 5 is 43
When dealing with arrays, just remember that the indexation begins at 0. You can read more about arrays here: http://www.dmc.fmph.uniba.sk/public_html/doc/Java/ch5.htm#:~:text=An%20array%20is%20a%20collection,types%20in%20a%20single%20array.
A tip: it's gonna be easier to help if you post the code on your question as a text, not an image, so we can copy it and try it on.
Approach 1 :
You can use ArrayList from Collection Classes and store the result there and after the loop is completed, just print the array in a loop.
Example :
//Import class
import java.util.ArrayList;
//Instantiate object
ArrayList<String> output = new ArayList();
while(condition){
output.add("Your data");
}
for(i = 0; i < condition; i++){
System.out.println(output.get(i));
}
Approach 2 :
Use StringBuilder class and append the output to the string, after the loop is completed, print the string from stringbuilder object.
Example :
//import classes
import java.util.*;
//instantiate object
StringBuilder string = new StringBuilder();
while(condition){
string.append("Your string/n");
}
System.out.print(string.toString());
Approach 3 : (As mentioned by Sarah)
Use arrays to store the result percentage or whatever and format it later in a loop. (Not a feasible approach if you want to store multiple values for the same student)
Example :
int studentMarks[] = new int[array_size];
int i = 0;
while(condition){
studentMarks[i++] = marks;
}
for(int j = 0; j < i; j++)
System.out.println("Marks : " + studentMarks[j]);
Why does the second while loop while (numberOfTries < 2) cancel both while loops? It runs perfect if there is no incorrect answer. But let's say I select 4 problems to be made, and I am only on the first problem. I give the incorrect answer 2 times so the program should say Incorrect two times and then give me a new question because while (numberOfTries < 2) should force it to break from that loop. But it doesn't, it just quits the whole thing. I know it has to be a logic issue, so what am I missing?
import java.util.Random;
import java.util.Scanner;
public class Howthe {
public static void main(String[] args) {
// Open Scanner
Scanner scan = new Scanner(System.in);
// Ask user to choose number of problems to be made.
// Can only choose 4, 9, or 16
System.out.print("Choose a number of problems to be made (4, 9, 16): ");
int userChoiceOfProblems = scan.nextInt();
// Ask user to choose a number between 0 and 12
System.out.print("\nChoose a number between 0 and 12: ");
int userNumberBetween0and12 = scan.nextInt();
// Ask user to choose between add/sub or multiply/divide
System.out.println("\nChoose to:"
+ "\n0: add/sub your chosen number"
+ " and the randomly generated number: "
+ "\n1: multiply/divide your chosen number"
+ " and the randomly generated number: ");
int userArithmeticChoice = scan.nextInt();
int counter = 0;
String equationString;
int equationAnswer;
int numberOfAnswersRight = 0;
int numberOfTries = 0;
int userAnswerToQuestion;
if (userArithmeticChoice == 0){
while (counter < userChoiceOfProblems){
// Create random number to decide if add or sub used.
// add is equal to 0 and sub is equal to 1
Random rand = new Random();
int randomNumberBetween0and1 = rand.nextInt(1) + 0;
// Create random number that is multiplied by userNumberBetween0and12
int randomNumberBetween0and12 = rand.nextInt(12) + 0;
// Add and increase counter by 1
if (randomNumberBetween0and1 == 0){
// If numberOfTries is more than 2, then display answer.
while (numberOfTries < 2){
// Compute the right answer (addition).
equationAnswer = userNumberBetween0and12 + randomNumberBetween0and12;
// Produce string of equation, then display string (addition).
equationString = userNumberBetween0and12 + " + "
+ randomNumberBetween0and12;
System.out.println(equationString);
userAnswerToQuestion = scan.nextInt();
// If answer is right, increase numberOfAnswersRight.
if (userAnswerToQuestion == equationAnswer){
numberOfAnswersRight++;
System.out.println("Correct!");
break;
}
// If answer is wrong, continue loop and increase numberOfTries
else if (userAnswerToQuestion != equationAnswer){
numberOfTries++;
System.out.println("Incorrect");
}
} // end of while (numberOfTries < 2 && !quit)
counter++;
}
} System.out.println("Yout got " + numberOfAnswersRight + " problem(s) right!");
}
}
}
numberOfTries is initialized outside of your loops. Once you try twice, it never gets set back to 0 which causes the loops to skip and finish on the next question because numberOfTries is already 2.
My name is Fermin. I'm new in this forum and I'm also studying Java to be a Java developer. I'm stuck on an assignment and I would like some help from anyone. Here is the description and the code
Using an if statement in the for block, determine
whether randNum and guessNum are equal.
public class GuessGame {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
int randNum , guessNum ;
//Generates a random number from 1 to 10
randNum = new java.util.Random().nextInt(10) + 1;
System.out.println("Im thinking of a number from 1 to 10");
for (guessNum = 0; guessNum <= 10; guessNum ++){
java.util.Scanner scan = new java.util.Scanner(System.in);
guessNum = scan.nextInt();
if (guessNum == randNum) {
System.out.println("you guess" + guessNum );
}
}
}
}
Updated code
import java.util.Random;
import java.util.Scanner;
public class NumberGuess {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Random rand = new Random();
System.out.println("Im thinking of a number from 1 to 10");
int number = scan.nextInt(10);
//Generates a random number from 1 to 10
int number2 = rand.nextInt(10)+1;
System.out.println("you enter the number" + " " + number);
for (int counter = -1; counter < 3; counter ++ ){
if(number!= number2)
System.out.println("and your random number is:" + " " + number2 + " " + "please try again");
else
System.out.println("your guess number is equal to the random number Good job guessing");
break;
}
}
}
Your for loop is controlled by the guessNum variable. Within the loop, you're reassigning that variable's value when you do this:
guessNum = scan.nextInt();
As a result, you're likely getting an inconsistent number of loops because you're changing the variable that the loop relies on for control.
Given the name of this variable, I suspect you originally intended it to be used to store the user's input. If that is the case, I would alter your for loop to use a different variable instead, like so:
for (int guessCount = 0; guessCount < 10; guessCount++){
Also note, your condition originally had <= 10; since your counting variable started at zero, this will allow the user 11 guesses, rather than 10 (since 0 to 10 inclusive = 11). Assuming you wanted 10 guesses instead, you will want to check for less than 10 (since 0..10 exclusive = 10).
import java.util.Random;
import java.util.Scanner;
public class NumberGuess {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Random rand = new Random();
System.out.println("Im thinking of a number from 1 to 10");
int number = scan.nextInt(10);
//Generates a random number from 1 to 10
int number2 = rand.nextInt(10)+1;
System.out.println("you enter the number" + " " + number);
for (int counter = -1; counter < 3; counter ++ ){
if(number!= number2)
System.out.println("and your random number is:" + " " + number2 + " " + "please try again");
else
System.out.println("your guess number is equal to the random number Good job guessing");
break;
}
}
}