Think java chapter 3 exercise 3-4 - Guess My Number - java

Hey guys I'm working some exercises from the Think java textbook. I'm working on exercise 3-4 on chapter 4 and I finished writing the code and it works when I run it the first few times but when I try running it again it prints the number generated not the number guessed.
import java.util.Random;
import java.util.Scanner;
public class GuessMyNumber {
//exercise 3-4
public static void main (String[]args) {
//pick a number
int numberGuessed;
int numberGenerated;
int difference;
//generate a random number
Random random = new Random();
numberGenerated = random.nextInt(100) + 1;
Scanner sc = new Scanner(System.in);
//prompt for user input
System.out.println("Im Thinking of a Number between 1 and 100 \nCan you Guess what it is? ");
System.out.print("Type a Number: ");
numberGuessed = sc.nextInt();
System.out.println("Your Guess is: " + numberGuessed);
System.out.println("The Number I was Thinking of is: " + numberGenerated);
//modulation operator
difference = numberGenerated % numberGuessed;
System.out.println(difference);
System.out.printf("you were of by: %d", difference);
}
}

I think what you are confused about is the modulo operation. At least the text does not fit to what it is doing. To calculate what was the difference between the two numbers you would just do
difference = numberGenerated - numberGuessed;
When you don't want to have negative values you could use
difference = java.lang.Math.abs(numberGenerated - numberGuessed);
The modulo operator gives you the rest of a division.

Related

why is my program displaying the array wrong?

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

Is there a way to prevent decimal output of a double calculation?

Got this code here and I was wondering if it were possible to make the output that comes from either calculation systems be without a decimal/stop the value at the point before the decimal point. Or even convert a double to an int without any errors.
Please ignore the pointless do while loop at the start, I am aware.
Thank You for any help.
class Main{
public static void main(String[] args)
{
calculation(getSystemChoice());
}
public static int getSystemChoice()
{
Scanner input = new Scanner(System.in); //create scanner
int systemChoice;
do{
System.out.println("If you are using the Metric system, please enter a 1.");
System.out.println("If you are using the Imperial system, please enter a 2.");
System.out.println("To quit the program, please enter a 3.");
systemChoice = input.nextInt();
//Switch start
switch(systemChoice){
case 1:
systemChoice=1;
return systemChoice;
case 2:
systemChoice=2;
return systemChoice;
default: //Currently no working input correction system, likely due to no case for 3. !!!!
System.exit(0);
}
//Switch End
}
while(systemChoice != 1 || systemChoice != 2 || systemChoice != 3);
return systemChoice;
}
//This method takes an int as a parameter(1 or 2) and runs if statements based on the metric or imperial systems.
public static void calculation(int systemChoice)
{
double inches, centimeters, meters, feet;
Scanner input = new Scanner(System.in); //create scanner
//if the user entered one, the result will be in meters and centimeters
if(systemChoice == 1){
System.out.print("Enter amount of meters: ");
meters = input.nextDouble();
System.out.print("Enter amount of centimeters: ");
centimeters = input.nextDouble();
feet = meters * 3.28084;
inches = centimeters / 2.54;
System.out.printf("Feet: %.2f\t " , feet);
System.out.printf("Inches: %.2f\t " , inches);
rerun(systemChoice);
}
// if the user entered 2 then the result will be in feet and inches
else if(systemChoice == 2){
System.out.print("Enter amount of feet: ");
feet = input.nextDouble();
System.out.print("Enter amount of inches: ");
inches = input.nextDouble();
meters = feet / 3.28084;
centimeters = inches * 2.54;
System.out.printf("Meters: %.2f\t " , meters);
System.out.printf("Centimeters: %.2f\t\n " , centimeters);
rerun(systemChoice);
}
}
public static void rerun(int systemChoice)
{
Scanner in = new Scanner(System.in);
System.out.println("\nIf you would like to make another measurement, enter 4.");
System.out.println("Otherwise, you may quit by entering any other number.");
systemChoice = in.nextInt();
if(systemChoice == 4)
{
getSystemChoice();
calculation(systemChoice);
}
else
{
System.exit(0);
}
}
}
You can use casting just before you print it and print it as an integer.
System.out.printf("Inches: %d " , (int)inches)
I do not recommend simply casting to int. Here is an example:
double myValue = 8.65;
System.out.println((int) myValue); // will output 8 as java will always round to the next lower integer
System.out.println(Math.round(myValue)); // will output 9 which obviously is correct (mathematically speaking)
There are a number of potential solutions depending on your exact requirements. Other posters have already mentioned a couple. It's worth bearing in mind the pros and cons of each:
Simply casting to an int or long is the simplest method, but will always round down. It's probably fine for your training example. But in real-world applications, this can cause subtle bugs with values that a double can represent but an int or long can't (e.g. a double can represent the result of 1.0/0 as "infinity", but casting to an int or long will turn this into a large positive integer value-- that can lead to subtle bugs in real-world applications);
You can use Math.round() to use the convention of rounding to up or down to the 'nearest' integer; but this doesn't solve the issue of values that can't be represented;
For other rounding modes, you can use the BigDecimal class: see the BigDecimal.round() method-- many applications won't require this, but some specialist cases might;
To truncate to zero decimal places for output while also dealing with 'special' values, you can use String.format() and specify zero decimal places.
The code for the latter option would look as follows:
double val = ...
System.out.printf("Truncated value is: %.0f", val);
You've probably already seen the 'simple casting' option, but it would look like this:
double val = ...
long truncatedVal = (long) val;
System.out.println("Truncated value = " + truncatedVal);

How do I display a message that tells the user how far off their guess was from the randomly generated number?

Hello my task is to write a program that selects a random number between 1 and 5 and asks the user to guess the number. Then I must display a message that indicates the difference between the random number and the users guess. I then must display another message that displays the random number and the Boolean value true or false depending on whether the user's guess equals the random number. I have got the first part of the assignment done, where the user guesses a number and the computer generates a random number between 1 and 5, but I don't have a clue on how to make it display how close or far off they were or how to use a Boolean to show if the guess was equal to the number or not. I have left code of what I have so far. Thanks for the help and sorry if there is anything wrong with this post.
package randomguessmatch;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class RandomGuessMatch
{
public static void main(String[] args)
{
int random = 1 + (int)(Math.random() * 5);
Scanner input = new Scanner(System.in);
JOptionPane.showInputDialog(null,"Enter a number between 1 and 5: ");
JOptionPane.showMessageDialog(null,"The number is: " + random);
}
}
I need the first message to read something like "You were 3 numbers off." and the second message needs to read something like "You guessed the number 3 correctly" or "You did not guess the number 3 correctly."
Take the absolute value of the entered number subtracted by the random number.
Something like:
package randomguessmatch;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class RandomGuessMatch
{
public static void main(String[] args)
{
int random = 1 + (int)(Math.random() * 5);
Scanner input = new Scanner(System.in);
JOptionPane.showInputDialog(null,"Enter a number between 1 and 5: ");
JOptionPane.showMessageDialog(null, "You were " + Math.abs(random - parseInt(input)) + " away");
JOptionPane.showMessageDialog(null,"The number is: " + random);
}
}
Based on Zachary McGee's answer:
public static void main(String[] args)
{
int random = 1 + (int)(Math.random() * 5);
String input = JOptionPane.showInputDialog(null,"Enter a number between 1 and 5: ");
if(Integer.parseInt(input) == random)
JOptionPane.showMessageDialog(null, "You guessed correctly!");
else
JOptionPane.showMessageDialog(null, "You were " + Math.abs(random - Integer.parseInt(input)) + " away");
JOptionPane.showMessageDialog(null,"The number is: " + random);
}
If you have any questions to the code, feel free to ask :)

Subtracting from an Integer within a do-while loop

I'm generally new to programming and just started programming in Java a few days ago so I'm not sure if what I'm trying to accomplish is even possible with the way my program is coded.
I'm basically writing a program that asks for a "Strength" value between 0 and 9. It asks you to choose a weapon ((1) Knife is the only one available). It takes that information and generates a random damage ratio between 1-3 plus what ever number your strength is and is supposed to keep subtracting that value from 20 until it hit 0 then quits.
The problem is that I'm stuck in a loop. It subtracts the value from 20, but starts over and keeps subtracting from 20 again rather than storing the subtracted number.
Does anyone have any advice on how something like this would be accomplished? Any help is very much appreciated. This is my code so far....
package untitledgame;
import java.util.Random;
import java.util.Scanner;
public class UntitledGame {
public static void main(String[] args){
int pStrength, wKnife, damage, enemyDamage;
Scanner in = new Scanner(System.in); //used for next to int inputs
System.out.println("Choose Your Strength (0-9)");
pStrength = in.nextInt();
System.out.println("Your Strength Is "+pStrength);
System.out.println("Choose Your Weapon; (1)Knife");
wKnife = in.nextInt();
System.out.println("Press ENTER to battle...");
Scanner scanner = new Scanner(System.in); //waits for users to continue
scanner.nextLine();
if (wKnife == 1){
do {
int enemyHP = 20;
Random rn = new Random(); //Random generator
wKnife = rn.nextInt(3) + 1; //Randomly generates knife damage
damage = wKnife + pStrength; //Damage logic
System.out.println("Attack with knife has done: " ); //Knife damage
System.out.print(+damage);
System.out.print(" damage." );
System.out.println("");
enemyDamage = enemyHP - damage; // Remaing HP
System.out.println("Enemy has ");
System.out.print(+enemyDamage);
System.out.print(" HP left.");
System.out.println("");
System.out.println("Press Enter to Attack...");
scanner.nextLine();
}
while (enemyDamage > 0);
System.out.println("Enemy has been defeated.");
}
}
}
Declare this int enemyHP = 20; outside the do-while loop. Right now, you're resetting enemyHP to 20 every single time you iterate through the loop.
Also, you should not recreate your Random within the do-while loop. Do that before entering the do block.
There are other issues with the logic that Jonah Haney deals with in his answer.
You'll want to initialize your enemyHP variable OUTSIDE of the do-while loop, or it will reset enemyHP back to 20 every time it loops.
Declare int enemyHP = 20 before the beginning of the loop. Then your loop is missing the following line:
enemyHP = enemyHP - damage;
Also, it seems that you want the loop to keep running until the enemy has been defeated. If that is the case, then your condition should check to see if enemyHP has been drained all the way, like this:
}
while (enemyHP > 0); //instead of while (enemyDamage > 0);
EDIT
This is what your code SHOULD look like. I am not saying you should copy it straight into your project. I am saying that you should take a look at the differences and it will help you see the logic problems in your own code:
public static void main(String[] args){
int pStrength, wKnife, damage, enemyDamage;
Scanner in = new Scanner(System.in); //used for next to int inputs
System.out.println("Choose Your Strength (0-9)");
pStrength = in.nextInt();
System.out.println("Your Strength Is " + pStrength);
System.out.println("Choose Your Weapon; (1)Knife");
wKnife = in.nextInt();
System.out.println("Press ENTER to battle...");
in.nextLine();
in.nextLine();
Random rn = new Random(); //Random generator
int enemyHP = 20;
if (wKnife == 1){
do {
System.out.println("Press Enter to Attack...");
in.nextLine();
wKnife = rn.nextInt(3) + 1; //Randomly generates knife damage
damage = wKnife + pStrength; //Damage logic
System.out.println("Attack with knife has done: " + damage + " damage."); //Knife damage
enemyHP -= damage; // Calculate Remaining HP
System.out.println("Enemy has " + enemyHP + " HP left.");
} while (enemyHP > 0);
System.out.println("Enemy has been defeated.");
in.close();
}
}

Java Dice Roller Loops

So I am having an issue figuring out how to create a loop and bring another class over in a dice game application I have to create for a school project. The game has to keep user score for each round 18 is the max score and if a user Rolls over 10 in 1 round his points are lost and he starts the next round at 1 point. The game also has to validate when the user enters Y to Roll or R to stop. Some help on this would be greatly appreciated. Im having problems with setting up a loop in which to continue the game after Y is entered or Tell the user the game has stopped after R is entered. So after Y is entered the loop would Print out "Round1" Roll:6 [Y or R], user entered Y, Print out "Round 2" and so on and i dont know how to validate user input.
import java.util.Scanner;
import java.util.Random;
import java.lang.Boolean;
public class Player {
public static void main(String[] args){
String player;
String playerAnswer;
Boolean answer = true;
int RoundScore;
int TotalScore;
int playerScore;
int Round;
Scanner user = new Scanner(System.in);
System.out.println("Enter your First Name to play!");
player = user.nextLine();
playerAnswer = user.nextLine();
{
System.out.println("Your Name:" + "" + player);
System.out.println("Welcome" + "" + player + "" + "To Dice Game");
System.out.println("Enter Y to Roll or R to STop:[Y or R]" + "" + playerAnswer.toUpperCase());
}
}
}
package Project4;
import java.util.Random;
import java.util.Scanner;
public class Dice{
public static void main(String[] args){
Random dice = new Random();
int number = 0;
for(int counter = 1; counter <= 1; counter++)
number = 1 + dice.nextInt(18);
System.out.println(number + "");
}
}
Something for you to note I don't think there's a (1) die can roll up to 18. The range for 3 dice should be 3 - 18 instead of 1 - 18.
number = 3 + dice.nextInt(16);
For the loop issue use do while loop, and assign a variable to get the and noticed how your playerAnswer should be under the System.out.println.
int rounds = 1;
do {
// codes that you want to loop
System.out.println("Welcome" + "" + player + "" + "To Dice Game");
System.out.println("Round " + rounds); // this will annouce the number of rounds
System.out.println("Enter Y to Roll or R to STop:[Y or R]")
playerAnswer = user.nextLine();
rounds++;
} while (playerAnswer.equalsIgnoreCase("y");
Also, I don't think you can have 2 main method here as you're creating "an" application, not 2 different application. I would suggest that you create a sub method using
public static void rollDice()
{
// codes for rolling the dice
}
and to call the rollDice method just do a
rollDice();
However, the application you're creating seems to be small and doing just the dice roll, if I am you I wouldn't even need to create a method for it.
You are probably trying to learn how to create a class. Seeing your codes, you seems like you aren't that great in Java yet. I would suggest that you re-start learning Java from the basics. I think you need to pay more attention in your school class.

Categories

Resources