I'm new to java and I have a project that I am working on in school. When I run the program, it gives me everything I ask, except the fact that it prints "The number is bigger" above the answer. Is there anything I am missing? Thanks
import java.util.Scanner;
import java.util.Random;
public class Project {
public static void main(String[] args) {
{
Scanner reader = new Scanner(System.in);
int numberOfGuesses = 0;
int x = 0;
Random rand = new Random();
int randomNumber = rand.nextInt(100) + 1;
while (x != 1) {
System.out.print("Guess an integer between 1 and 100: " );
int guessedNumber = reader.nextInt();
if (guessedNumber < randomNumber) {
System.out.println("The number is bigger");
}
if (guessedNumber > randomNumber) {
System.out.println("The number is smaller");
}
else{
x++;
}
numberOfGuesses++;
}
System.out.println("You're correct! It took" + " " + numberOfGuesses + " " + "guesses.");
}
}
}
if (guessedNumber < randomNumber) {
System.out.println("The number is bigger");
}
if (guessedNumber > randomNumber) {
System.out.println("The number is smaller");
}
else{
x++;
}
TO
if (guessedNumber < randomNumber) {
System.out.println("The number is bigger");
} else if (guessedNumber > randomNumber) {
System.out.println("The number is smaller");
} else{
x++;
}
When the number is bigger, your second if fails and goes to its else part which increments x to 1 and exists the program. put the second if statement as else if.
if (guessedNumber < randomNumber) {
System.out.println("The number is bigger");
}
else if (guessedNumber > randomNumber) {
System.out.println("The number is smaller");
}
else{
x++;
}
Related
I cannot figure out how to add a limit to the number of guesses in my number guessing game. I have tried adding a for statement after the while statement but that made the code just stop at the tenth guess and there was no winner ever. I deleted the while statement and just did the for statement which ensured that the user got the correct answer every ninth guess. My code is divided into two classes as requested by my professor. I am including both below. I would appreciate all the help I can get. Thank you!
GuessingGame.java: Main Class
public class GuessingGame {
public static void main(String[] args) {
new Guess().doGuess();
}
}
Guess.java
class Guess {
private int answer = 0;
int tries = 0;
Scanner input = new Scanner(System.in);
int guess, i;
boolean win = false;
int amount = 10;
public Guess() {
answer = generateRandomNumber();
}
//Generate a private number between 1 and a thousand
private int generateRandomNumber() {
Random rand = new Random();
return rand.nextInt(1000) + 1;
}
public void doGuess() {
while(!win) {
System.out.println("You are limited to ten attempts."
+ "Guess a number between 1 and 1000: ");
guess = input.nextInt();
if (guess > 1000 ) {
System.out.println("Your guess is out of the range!");
} else if (guess < 1) {
System.out.println("Your guess is out of the range!");
} else if (guess == answer) {
win = true;
tries++;
} else if (guess < answer && i != amount -1) {
System.out.println("Your guess is too low!");
tries++;
} else if (guess > answer && i != amount -1) {
System.out.println("Your guess is too high!");
tries++;
}
}
System.out.println("Congragulations! You guessed the number!"
+ "The number was: " +answer);
System.out.println("It took you " + tries + " tries");
}
}
You can add an if-statement inside the while loop.
public void doGuess() {
while(!win) {
System.out.println("You are limited to ten attempts."
+ "Guess a number between 1 and 1000: ");
guess = input.nextInt();
if(tries > 9) {
...whatever you want to happen when user has reached 10 guesses...
}
For my Java class, I'm supposed to make a random number guessing game. I've been stuck on a loop I created for the past couple of days. The output of the program is always an infinite loop and I can't see why. Any help is very much appreciated.
/*
This program will generate a random number.
It will ask the user to guess what number was generated and say
if the guess is too high or low.
*/
import java.util.Scanner;
import java.util.Random;
public class RandomNumGame {
public static void main(String[] args) {
Random rand = new Random();
Scanner input = new Scanner(System.in);
int randNum = rand.nextInt(20);
System.out.println("Number is : " + randNum);
int userGuess = 0;
int success = 0;
System.out.println("Guess the number: ");
userGuess = input.nextInt();
while(success == 0)
{
if(userGuess > randNum){
System.out.println("Too high");
}
else if(userGuess < randNum){
System.out.println("Too high");
}
else{
System.out.println("Something is very wrong.");
}
}
if(userGuess == randNum){
success++;
System.out.println("You got it! Play again?");
}
}
}
You put the if that checks if the input is equal to the number outside the while, so the cycle never ends.
Here is the code fixed:
import java.util.Scanner;
import java.util.Random;
public class RandomNumGame {
public static void main(String[] args) {
Random rand = new Random();
Scanner input = new Scanner(System.in);
int randNum = rand.nextInt(20);
System.out.println("Number is : " + randNum);
int userGuess = 0;
int success = 0;
System.out.println("Guess the number: ");
userGuess = input.nextInt();
while(success == 0) {
if(userGuess > randNum) {
System.out.println("Too high");
} else if(userGuess < randNum) {
System.out.println("Too high");
} else if(userGuess == randNum) {
success++;
System.out.println("You got it! Play again?");
} else {
System.out.println("Something is very wrong.");
}
}
}
}
I fixed it! I added breaks after each fail condition so that I wouldn't get an infinite loop. I tried this earlier, but I kept getting errors.
This is the completed code:
import java.util.Scanner;
import java.util.Random;
public class RandomNumGame {
public static void main(String[] args) {
Random rand = new Random();
Scanner input = new Scanner(System.in);
int randNum = rand.nextInt(20);
System.out.println("Number is : " + randNum);
int userGuess = 0;
boolean success = false;
System.out.println("Guess the number: ");
userGuess = input.nextInt();
input.close();
while(success == false){
if(userGuess > randNum) {
System.out.println("Too high,try again");
break;
} else if(userGuess < randNum) {
System.out.println("Too low");
break;
} else if(userGuess == randNum) {
success = true;
System.out.println("You got it! Play again?");
} else {
System.out.println("Something is very wrong.");
}
}
}
}
I need help coding a set of statements of data validation that checks if a user entry is within a range of 0 and 100, and anything the user types that ISNT a non-decimal integer between 1 and 100 should display an error message. Also I need a way to code how I can get a "goodbye" output to only display if the user enters "n" not "n" and "y." N meaning no and y meaning yes.
Heres my code.
import java.util.Scanner;
public class GuessingGameCalc {
private static void displayWelcomeMessage(int max) {
System.out.println("Welome to the Java Guessing Game!");
System.out.println(" ");
System.out.println("I'm thinking of a number between 1 and" + " " + max + " " + "let's see if you guess what it is!");
System.out.println(" ");
}
public static int calculateRandomValue(int max) {
double value = (int) (Math.random() * max + 1);
int number = (int) value;
number++;
return number;
}
public static void validateTheData(int count) {
if( count < 3) {
System.out.println("Good job!");
} else if (count < 7) {
System.out.println("Need more practice.");
} else{
System.out.println("Need way more practice.");
}
}
public static void main(String[] args) {
final int max = 100;
String prompt = "y";
displayWelcomeMessage(max);
int unit = calculateRandomValue(max);
Scanner sc = new Scanner(System.in);
int counter = 1;
while (prompt.equalsIgnoreCase("y")) {
while (true) {
System.out.println("Please enter a number.");
int userEntry = sc.nextInt();
if (userEntry < 1 || userEntry > max) {
System.out.println("Invalid guess! Guess again!");
continue;
}
if (userEntry < unit) {
if ( (unit - userEntry) > 10 ) {
System.out.println("Way Too low! Guess higher!");
} else {
System.out.println("Too low! Guess higher!");
}
} else if (userEntry > unit) {
if( (userEntry - unit) > 10 ){
System.out.println("Way Too high! Guess lower!");
} else {
System.out.println("Too high! Guess lower!");
}
} else {
System.out.println("Congratulations! You guessed it in" + " " + counter + " " + "tries!\n");
validateTheData(counter);
break;
}
counter++;
}
System.out.println("Would you like to try again? Yes or No?");
prompt = sc.next();
System.out.println("Goodbye!");
}
}
}
Instead of using .nextInt() rather use .nextLine(), which returns a String and then parse it to an int and catch the NumberFormatException
So basically you'll have this structure:
try {
int userEntry = Integer.parseInt(sc.nextLine());
...
} catch (NumberFormatException nfe) {
System.out.println("Please enter a valid number.");
}
Oh, just a comment on the rest of your code. You don't really need two while loops, one will be more than sufficient.
After the programs reads the exception it stops.
A need a little help on how to make it continue to the beginning of the loop.
I tried the continue statement but it did not work or maybe my mistake.
package labexer5a;
import java.util.*;
public class LabExer5A {
public static void main(String[] args) {
int max = 50;
int min = 1;
int secretNumber;
secretNumber = (int)(Math.random() * 49 + 1);
Scanner keyboard = new Scanner(System.in);
int guess;
int count = 0;
try{
do{
System.out.println("Guess a number from 1 to 50");
guess = keyboard.nextInt();
count ++;
if(guess == secretNumber){
if(count> 1){
System.out.println("You got it in " + count + " attempt(s)");
}
else{
System.out.println("You got it in " + count + " attempt");
}
}
else if(guess > max){
System.out.println("Out of Range");
}
else if(guess < min){
System.out.println("Out of Range");
}
else if(guess > secretNumber){
System.out.println("Too High. Try Again");
}
else if(guess < secretNumber){
System.out.println("Too Low. Try Again");
}
}
while(guess != secretNumber);
}
catch(InputMismatchException e){
System.out.println("Invalid Input");
}
}
}
Move the try/catch inside the loop and place it around the specific code that throws an exception.
do{
System.out.println("Guess a number from 1 to 50");
try {
guess = keyboard.nextInt();
} catch (InputMismatchException e){
System.out.println("Invalid Input");
keyboard.readLine();
continue;
}
count ++;
// rest of code
while(guess != secretNumber);
I am not sure how you want to handle count when you get an exception, if you want to count every attempt even the incorrect one then move count++ to before you read from the scanner.
Try this:
public class LabExer5A {
public static void main(String[] args) {
int max = 50;
int min = 1;
int secretNumber;
secretNumber = (int)(Math.random() * 49 + 1);
Scanner keyboard = new Scanner(System.in);
// you should initiate the value. If there is no exception, it would be replaced by the value read from console.
int guess = Integer.MAX_VALUE;
int count = 0;
do{
System.out.println("Guess a number from 1 to 50");
try {
guess = keyboard.nextInt();
} catch(InputMismatchException e){
System.out.println("Invalid Input");
// you should really read the input
keyboard.next();
count ++;
continue;
}
count ++;
if(guess == secretNumber){
if(count> 1){
System.out.println("You got it in " + count + " attempt(s)");
}
else{
System.out.println("You got it in " + count + " attempt");
}
}
else if(guess > max){
System.out.println("Out of Range");
}
else if(guess < min){
System.out.println("Out of Range");
}
else if(guess > secretNumber){
System.out.println("Too High. Try Again");
}
else if(guess < secretNumber){
System.out.println("Too Low. Try Again");
}
}
while(guess != secretNumber);
}
}
package labexer5a; import java.util.*;
public class LabExer5A {
public static void main(String[] args) {
int max = 50;
int min = 1;
int secretNumber;
secretNumber = (int)(Math.random() * (max-1) + min);
Scanner keyboard = new Scanner(System.in);
int guess;
int count = 0;
do {
System.out.println("Guess a number from "+min+" to "+max);
try{
guess = keyboard.nextInt();
}
catch(InputMismatchException e){
System.out.println("Invalid Input");
continue;
} finally { // don't forget finally clause to increase count
count ++;
}
if(guess == secretNumber){
if(count> 1){
System.out.println("You got it in " + count + " attempt(s)");
}
else{
System.out.println("You got it in " + count + " attempt");
}
}
else if(guess > max){
System.out.println("Out of Range");
}
else if(guess < min){
System.out.println("Out of Range");
}
else if(guess > secretNumber){
System.out.println("Too High. Try Again");
}
else if(guess < secretNumber){
System.out.println("Too Low. Try Again");
}
}
while(guess != secretNumber);
}
}
I have been trying to figure out why isn't my code working. If I don't do it through a method and put this code in the main method then it keeps repeating. I want to ask the user for a new number every time. And then see if the number is odd or even. If odd then increase the odd count add all the numbers that the user enters. The user should be asked to enter values until the number 0 is entered.
package Week1;
import java.util.Scanner;
public class Task12 {
public void numbers() {
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
System.out.println("Enter number");
int oddnumbers = 0;
do {
int count = 0;
count = count + i;
System.out.println("The total is:" + count);
if (i % 2 == 0) {
System.out.println("The number is Even");
} else if (i != 9) {
oddnumbers += i;
System.out.println("The number is odd");
System.out.println("the count of odd numbers is :" + oddnumbers);
} else
System.out.println("The number is odd");
System.out.println("the count of odd numbers is :" + oddnumbers);
} while (i != 0);
}
public static void main(String[] args) {
Task12 n = new Task12();
n.numbers();
}
}
You should probably have the reading of a number "i = sc.nextInt();" inside the loop, and the variable count outside, like this:
package Week1;
import java.util.Scanner;
public class Task12 {
public void numbers() {
Scanner sc = new Scanner(System.in);
int oddnumbers = 0;
int count = 0;
int i=0;
do {
System.out.println("Enter number");
i = sc.nextInt();
count = count + i;
System.out.println("The total is:" + count);
if (i % 2 == 0) {
System.out.println("The number is Even");
} else if (i != 9) {
oddnumbers += i;
System.out.println("The number is odd");
System.out.println("the count of odd numbers is :" + oddnumbers);
} else
System.out.println("The number is odd");
System.out.println("the count of odd numbers is :" + oddnumbers);
} while (i != 0);
}
public static void main(String[] args) {
Task12 n = new Task12();
n.numbers();
}
}
This code gives the answer to tour spec/question
Reason for not working: You should take input inside do while loop and then check for odd.
public int numbers() {
Scanner sc = new Scanner(System.in);
int num = 0;
int oddSum = 0;
do {
System.out.println("Enter number");
num = sc.nextInt();
if(num == 0) {
break;
} else if (num % 2 != 0) {
oddSum += num;
}
} while (num != 0);
sc.close();
return oddSum;
}
public static void main(String[] args) {
Test n = new Test();
System.out.println(n.numbers());
}