This very simple guess game does not work - java

I try to make a very simple guess game and i wanted to add an exciting addition by doing an analysis of the guesswork from the user using switch function but I was surprised that it did not run that analysis
public static void main (String args[]){
Scanner reader = new Scanner(System.in).useLocale(Locale.ROOT);
int num = 8 , guess;
boolean positiveguess = true;
while (positiveguess) {
System.out.println("Enter your guess = ");
guess = reader.nextInt();
if (guess != num)
switch(guess)
{
case '1':
if (num-5 < guess && num + 5 >guess)
System.out.println("Your guess is almost close! \nTry again ");
break;
case '2':
if (num-10 < guess && num + 10 >guess)
System.out.println("You need to guess again ");
break;
}
else
positiveguess = false;
}
System.out.println("Great !");

Your switch is based on the user input and not the difference between given and exepcted value. First I suggest you to keep it simple with if/else structure like
public class Main {
public static void main (String args[]) {
Scanner reader = new Scanner(System.in).useLocale(Locale.ROOT);
int num = 8, guess;
boolean positiveguess = true;
while (positiveguess) {
System.out.println("Enter your guess = ");
guess = reader.nextInt();
if (guess != num) {
if (num - 5 < guess && num + 5 > guess) {
System.out.println("Your guess is almost close! \nTry again ");
} else if (num - 10 < guess && num + 10 > guess) {
System.out.println("You need to guess again ");
}
} else {
positiveguess = false;
}
}
System.out.println("Great !");
}
}
Then I suggest you to remove your positiveguess and do a while loop with your condition inside. And use Math.abs() to get the difference between the guess and the expected value.
public class Main {
public static void main (String args[]) {
Scanner reader = new Scanner(System.in).useLocale(Locale.ROOT);
int num = 8;
int guess = Integer.MIN_VALUE;
while (guess != num) {
System.out.println("Enter your guess = ");
guess = reader.nextInt();
int diff = Math.abs(num - guess);
if (diff != 0) {
if (diff < 5) {
System.out.println("Your guess is almost close! \nTry again ");
} else if (diff < 10) {
System.out.println("You need to guess again ");
} else {
System.out.println("You're way too far bro");
}
}
}
System.out.println("Great !");
}
}

You are using switch wrongly here. It seems you are looking for something like this:
switch (guess) {
// first case
case (num-5 < guess && num + 5 >guess):
System.out.println("Your guess is almost close! \nTry again ");
// second case
case (num-10 < guess && num + 10 >guess):
System.out.println("You need to guess again ");
}
But this is not valid syntax. In Java, a switch/case can only compare elements to other elements of the same type (or, in newer version, multiple elements, or a class), not perform complex conditional checks like if can.
Probably you then tried to "fix" it by combining case '1' and the if statements, but while legal, case '1' will only be the case if guess is '1' (i.e. 49), and only then will continue to check the if condition.
Instead, just drop the switch/case and use your if statements directly (don't forget the else):
if (num-5 < guess && num+5 > guess) {
System.out.println("Your guess is almost close! \nTry again ");
} else if (num-10 < guess && num+10 > guess) {
System.out.println("You need to guess again ");
}
Also, you could make those checks more readable by changing the order to (num-5 < guess && guess < num+5) or using Math.abs to find the absolute difference and use that in the condition.

Related

Repeating a statement in while loop Java

Sorry for the newbish question, am quite new with Java.
So I want to display an error message when user input is outside of the bounds (Lesser than 0, greater than 100) which I've managed to do but I also want that the user can try again but my current code only continues with the execution of the program.
This is what I have now:
import java.util.Scanner;
public class storeQuota {
public static void main(String [] args) {
Scanner input = new Scanner (System.in);
int quotas [] = new int [100];
int NumberOfWorkers = 100;
for (int i = 0; i<numberOfWorkers; i++) {
if (i == 0) {
System.out.print("Enter the quota for the 1st student: ");
}
else if (i == 1) {
System.out.print("Enter the quota for the 2nd student: ");
}
else if (i == 2) {
System.out.print("Enter the quota for the 3rd student: ");
}
else if (i >= 3) {
System.out.print("Enter the quota for the " + (i+1) + "th student: ");
}
while (true) {
quotas[i] = input.nextInt();
if (quotas[i] > 100 || quotas[i] < 0)
System.out.println("Error - Can only be between 0 and 100.");
break;
}
}
//Printing all quotas.
System.out.println("Thank you for your input. Your entered quotas are: ");
for (int i=0; i<numberOfWorkers; i++)
{
System.out.print(quotas[i] + ", ");
}
input.close();
}
}
With this code, the error message is correctly displayed when a user inputs an int that isn't between 0 and 100 but the user will be unable to try again, the program continues to ask for the next quoata.
I think the problem is located in this line
break;
after
System.out.println("Error - Can only be between 0 and 100.");
which always breaks the while loop. Instead you only want to break the while loop if the input is in valid range. I would not use while(true) but some sort of conditional variable which is set to false in the while loop if the input is in valid range, also because while(true) is not a good programming practice from my point of view.
Your problem is using Break;
rather than using that, you should change the while(true) to while(false), you've also forgot to add curly brackets around the if statement.
boolean x = true;
while (x){
quotas[i] = input.nextInt();
if (quotas[i] > 100 || quotas[i] < 0){
System.out.println("Error - Can only be between 0 and 100.");
x = false;
}
}
also I suggest learning exceptions as they would make this 10x easier.
When executed, "break" breaks the loop you are currently in. In your code, break is executed irrespective of what the input is resulting in the unwanted result.
Simplest solution would be (closest to your original code):
while(true) {
quotas[i] = input.nextInt();
if (quotas[i] > 100 || quotas[i] < 0) {
System.out.println("Error - Can only be between 0 and 100.");
} else {
break;
}
}
Here, the loop will break only if correct input is entered.
You haven't used curly braces in if condition.
while (true) {
quotas[i] = input.nextInt();
if (quotas[i] > 100 || quotas[i] < 0) {
System.out.println("Error - Can only be between 0 and 100.");
break;
}
}

One expected line of output is not printed

import java.util.Random;
import java.util.Scanner;
public class Activity3 {
public static void main(String[] args) {
//Variables
Scanner input = new Scanner(System.in);
Random Machine = new Random();
int num = Machine.nextInt(10);
do {
System.out.println("Guess the random generated number of the machine from 1-10");
int guess = input.nextInt();
if (guess == num) {
System.out.println("Correct number= " + num);
System.out.println("You Win!");
} else if (guess <= 0 && guess >= 11) {
System.out.println("Invalid Number!");
}
if (guess > 1 && guess < 10){
System.out.println("You Lose:<");
}
System.out.println("Do you want to try again?");
} while (input.next().equalsIgnoreCase("YES"));
input.close();
}
}
If I guess the correct number it outputs " you win!".
If I guess wrong it outputs "you lose". But If I guess a number that isn't in 1-10 it doesn't output the "Invalid Number" and just proceeds to output the "Do you want to try again?".
Random#nextInt(int) will return a value from 0 to bound - 1, so it's possible that the guess could be 0 in your code. You'd correct this by adding 1 to the guess, for example int num = Machine.nextInt(10) + 1;
Look at your logic...
else if(guess <= 0 && guess >= 11) {
if guess <= 0 AND guess >= 11 ... well, that's impossible.
I would change your logic flow, focusing on "happy paths" first.
That is, is the input within the acceptable range? If so, is guess == num if so, you win, otherwise print error messages.
For example...
Scanner input = new Scanner(System.in);
Random Machine = new Random();
int num = Machine.nextInt(10) + 1;
boolean done = false;
do {
System.out.println("Guess the random generated number of the machine from 1-10");
// Read the WHOLE line of text, removing the new line from the
// buffer which would otherwise be left by Scanner#nextInt
// and would cause no end of issues
String text = input.nextLine();
try {
// Try and parse the text to an int
int guess = Integer.parseInt(text);
if (guess >= 1 && guess <= 10) {
if (guess == num) {
System.out.println("Correct number= " + num);
System.out.println("You Win!");
num = Machine.nextInt(10) + 1;
System.out.println("Would you like to play another game? (Yes/No)");
} else {
System.out.println("Incorrect, guess again");
System.out.println("Do you want to try again? (Yes/No)");
}
// Prompt the user to try again or play another game
text = input.nextLine();
done = !"yes".equals(text.toLowerCase());
} else {
System.out.println("Out of range");
}
} catch (NumberFormatException exp) {
System.out.println("Not a valid number");
}
} while (!done);

I want to write a program that allows the user to guess a number between 0 and 100 in 7 attempts. I don't know why is this not working

public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int rnd = (int)(Math.random() * 101);
System.out.println("The program is going to give a number that is between 0 and 100 (including them). You can guess it by pressing Run.");
System.out.println("Enter your number:");
int num = scan.nextInt();
for (int count = 1; count <= 7; count++) {
while (num != rnd) {
if (num < rnd) {
System.out.println("Your guess is too low.");
}
if (num > rnd) {
System.out.println("Your guess is too high.");
}
if ((Math.abs(rnd - num) == 1) || (Math.abs(rnd - num) == 2)) {
System.out.println("But your guess is VERY close.");
}
num = scan.nextInt();
}
System.out.println("You got it right!");
}
System.out.println("You should guess it in 7 tries.");
}
}
So I used two loops and just nested them. Is that how it works for this? Right now the code is like starting with for loop and if that is true it goes to the while loop part where the guessing number takes place. Can this be fixed with just moving some codes and fixing minor areas around?
What you should do in a situation like this is do the code manually. Literally. Grab a piece of paper and pretend you're a computer. It's a good exercise, and it will help you figure out your problem.
The problem is your inner loop. It loops until they guess correctly regardless of the number of attempts. Then you force them to do it 6 more times with the outer loop.
You really only need 1 loop. I would have a single loop like this:
int attempts = 0;
int num = 0;
do {
num = scan.nextInt();
... most of the if code from your inner loop but not another scan.nextInt
} while (++attempts < 7 && num != rnd);
// and here you look at num == rnd to see if success or failures
I think you should rebuild you code to make it more clear.
Split the title (with description of the task)
Split main loop where you read user input and check it with expected number
Split output of the final result, where you print the result.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
final int rnd = new Random().nextInt(101);
final int maxAttempts = 7;
System.out.println("The program is going to give a number that is between 0 and 100 (including them).");
System.out.println("You can guess it within maximum " + maxAttempts + " attempts by pressing Run.");
boolean success = false;
for (int attempt = 1; attempt <= maxAttempts && !success; attempt++) {
System.out.format("(%s of %s) Enter your number: ", attempt, maxAttempts);
int num = scan.nextInt();
if (num == rnd)
success = true;
else {
System.out.print("Your guess is too " + (num > rnd ? "high" : "low") + '.');
System.out.println(Math.abs(rnd - num) <= 2 ? " But it's VERY close." : "");
}
}
System.out.println(success ? "You got it right!" : "Bad luck this time. Buy.");
}
import java.util.Scanner;
class Main {
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int rnd = (int) (Math.random() * 101);
System.out.println("The program is going to give a number that is between 0 and 100 (including them). You can guess it by pressing Run.");
System.out.println("Enter your number:");
int num = scan.nextInt();
for(int count = 1; count <= 7; count++)
{
if (num < rnd)
{
System.out.println("Your guess is too low.");
}
else if (num > rnd)
{
System.out.println("Your guess is too high.");
}
else if ((Math.abs(rnd - num) == 1) || (Math.abs(rnd - num) == 2))
{
System.out.println("But your guess is VERY close.");
}
else
System.out.println("You got it right!");
System.out.println("Enter Next number: ");
num = scan.nextInt();
}
}
}
It should work Fine.Basically Your reasoning wass wrong because You are putting a while loop inside a for loop. What you want to do is you want only 7 iteration.In those 7 iterations you are checking the conditions based on user Input.

Using method to find an integer repeatedly

Hello my purpose is this:
Write a method that can accept values only between 10 and 50.Sample execution:Enter a number between 10 and 50Enter a number: 5Enter a number between 10 and 50Enter a number: 12Number Entered: 12.Enter a number: 0Good ByeSo as you can see it only finishes when user enters 0.And it says different things when number is between 10 and 50 or not.I deleted again my code and started but i got stuck on some points and i gave up.My final code was:
import java.util.Scanner;
public class A{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter case number: ");
int caseVal = scan.nextInt();
switch(caseVal){
case 1:
System.out.println("Enter a number between 10 and 50");
System.out.println("Enter a number: ");
int num = scan.nextInt();
betweenMethod(num);
if(num == 0){
System.out.println("Good Bye");
break;
}
while(num != 0){
betweenMethod(num);
}
break;
case 2:
System.out.println("Enter a number to display its divisors: ");
int x = scan.nextInt();
System.out.println("The divisors of " + x + " are:");
divisorsMethod(x);
break;
}
scan.close();
}
public static void divisorsMethod(int a){
if(a <= 0)
System.out.println("The number should be greater than 0");
else{
for(int b = 1; b <= a; b++){
if(a % b == 0 && b != a)
System.out.print(b + ", ");
else if(b == a)
System.out.println(b);
}
}
}
public static void betweenMethod(int a){
Scanner inputscan = new Scanner(System.in);
if(a >= 10 && a <= 50){
System.out.println("Enter a number:");
a = inputscan.nextInt();
}
else if((a < 10 || a > 50) && a != 0){
System.out.println("Enter a number between 10 and 50");
System.out.println("Enter a number:");
a = inputscan.nextInt();
}
else{
System.out.println("Good Bye");
}
inputscan.close();
}
}
Sorry for uncut version.It is case 1.Every time i tried it didnt work fully.If anyone can help i would appreciate it.I'm sorry if i didnt write this question in rules.(Sorry for the grammar as well)THIS IS WHERE I AM STUCK= When i type 0 it doesnt say GoodBye and end the loop.Thats where i need help.TO EVERYONE THAT NEEDS ANSWER TOO:I figured out what to do.Basically we say while its not equal to zero right?I wrote a new method that (after last inputscan for variable)checks if the number is zero and prints good bye.So with this way it prints good bye and it goes to starting.But it cannot do anythink else because we said while not equal to 0.Anyway thats one solution.
Don't close() System.in
When you call inputscan.close() that closes the underlying InputStream, which is System.in.
Return the Value
Your method should be prompting for input between two values and returning a single value. Also, you could move your Scanner to a static (or class) field. Something like
private static Scanner inputscan = new Scanner(System.in);
public static int betweenMethod(final int a, final int b) {
int min = Math.min(a, b);
int max = Math.max(a, b);
while (true) {
System.out.printf("Please enter a number between %d and %d%n", min, max);
int in = inputscan.nextInt();
if ((in == 0) || (in >= min && in <= max)) {
return in;
}
}
}
Primitives1 are Passed-By Value
You need to assign the result of the call back to your value when you loop. Something like,
int num = betweenMethod(10, 50);
while (num != 0) {
System.out.printf("Number Entered: %d.%n", num);
num = betweenMethod(num);
}
System.out.println("Good Bye");
break;
1and Everything Else in Java.

How can I code a console-based Java game to replay when the user types in "1"?

First of all, I'd like to say that I am REALLY new to all of this... I've tried learning as much as I can, so apologies if any of my code seems ridiculous or all-over-the-place, but I needed somewhere to start. (By the way, credit to the very base of this code goes to CrossCoastGaming: http://tinyurl.com/kktyq4e).
Now to the matter at hand. I have improved (for lack of a better word) on the coding that the man in the video shows, by adding several different phrases, making use of variables and adding a try counter. Here is my code:
import java.util.Random;
import java.util.Scanner;
public class Main {
public static int number, guess, tryCount, replay;
public static int maxValue =1;
public static Scanner scan;
public static Random rand;
public static void main(String args[]) {
scan = new Scanner(System.in);
rand = new Random();
System.out.print("Enter a maximum number: ");
while(maxValue < 2)
maxValue = scan.nextInt();
number = rand.nextInt(maxValue);
System.out.print("Guess a number from 1 to " + maxValue + ": ");
while (guess != number) {
guess = scan.nextInt();
tryCount++;
if (guess < 1) {
System.out.print("Guess is not positive. Try again: ");
}else if (guess < number) {
System.out.print("Too low! Try again: ");
}
if (guess > maxValue) {
System.out.println("Guess is higher than " + maxValue + ". Try again: ");
}else if (guess > number) {
System.out.print("Too high! Try again: ");
}
}
if (tryCount == 1) {
System.out.println("Nailed it! It only took you 1 try!");
}
else {
System.out.println("Nailed it! It took you " + tryCount + " tries.");
}
System.out.println("Type 0 to play again. Type 1 to quit.");
if (replay == 1) {
replay = scan.nextInt();
}
}
}
Ok, so hopefully that gives anyone who knows what they're doing an idea of my goal. Now, as you can see by this line:
if (replay == 1) {
replay = scan.nextInt();
}
I would like to write a way so people can replay the game without having to reboot the file. I already have an idea of what I kind of would like to do, but I've searched everywhere and can't seem to find out what to continue with after this point. I'm sure that I'm missing something. Any help would be greatly appreciated.
You can use a do-while loop to achieve this:
import java.util.Random;
import java.util.Scanner;
public class Main {
public static int number, guess, tryCount, replay;
public static int maxValue = 1;
public static Scanner scan;
public static Random rand;
public static void main(String args[]) {
scan = new Scanner(System.in);
rand = new Random();
do { // start of do-while loop
tryCount = 0; // reset tryCount
System.out.print("Enter a maximum number: ");
while(maxValue < 2) {
maxValue = scan.nextInt();
}
number = rand.nextInt(maxValue);
System.out.print("Guess a number from 1 to " + maxValue + ": ");
while (guess != number) {
guess = scan.nextInt();
tryCount++;
if (guess < 1) {
System.out.print("Guess is not positive. Try again: ");
} else if (guess < number) {
System.out.print("Too low! Try again: ");
}
if (guess > maxValue) {
System.out.println("Guess is higher than " + maxValue + ". Try again: ");
} else if (guess > number) {
System.out.print("Too high! Try again: ");
}
}
if (tryCount == 1) {
System.out.println("Nailed it! It only took you 1 try!");
} else {
System.out.println("Nailed it! It took you " + tryCount + " tries.");
}
do { // check the user's input
System.out.println("Type 0 to play again. Type 1 to quit.");
replay = scan.nextInt();
if (replay != 0 && replay != 1) {
System.out.println("Input not recognized.");
}
} while (replay != 0 && replay != 1);
} while (replay == 0); // end of do-while loop
}
}
do-while loops are always executed at least once. The condition is checked at the end of the loop.

Categories