I am trying to create a simple program which creates a random number and asks the user to guess. It will then say higher or lower until the user guesses correct. The problem is, after the user guesses correctly the program will keep looping. I thought that putting the code into a separate method and then calling it in a while loop would work but unfortunately it was no avail. Could anyone suggest how I would correct this?
Below is my code.
package main;
public class NumberGuesser {
public static void main(String[] args) {
code mycode = new code();
while (mycode.guess != mycode.random){
mycode.codebit();
}
}
}
package main;
import java.util.Random;
import java.util.Scanner;
public class code {
Random rand = new Random();
int random = rand.nextInt(1000);
double guess;
public void codebit(){
System.out.println("Guess the number");
Scanner input = new Scanner(System.in);
Double guess = input.nextDouble();
if (guess > random){
System.out.println("Lower");
}
else if (guess < random){
System.out.println("Higher");
}
else if (guess == random){
System.out.println("Well done");
}
}
}
You are re-declaring guess within your method body, which hides your instance member.
Try removing:
Double guess = input.nextDouble();
... and replacing with:
guess = input.nextDouble();
Also non-related to your issue:
As general coding guidelines go, class names should be CamelCase
You don't need to instantiate a Scanner each time. If you experiment with your code structure, you'll be able to have more efficient usage. Just a hint, try looking for the hasNext[...] methods of Scanner.
Double guess = input.nextDouble();
You're initializing a local variable which has the same name as the field here. The field, that is checked by the main class, is never modified. Also, why do you use a double and not an int for the guess?
I think you do not have to go into a separate method here. Just put the code you have in your code class into your main method into an infinite loop. This way, you will be able to stop the program by returning when the guess is correct:
else if (guess == random) {
System.out.println("Well done");
return;
}
your global value guess never be assigned with a value except it first assign a value (that is 0) from system as global variable.
This is caused as you declared a local variable and assigning the local variable every time instead global variable as default java properties.
Removing the declaration of local variable guess can be a solution of that problem. You can solved it other ways to like assign global with local using this.guess = guess.
I'm also pretty new to Java but I would keep it simple and do it like this:
package main;
import java.util.Random;
import java.util.Scanner;
public class GuessNumber {
public static void main(String[] args) {
Random rand = new Random();
Scanner input = new Scanner(System.in);
int guess;
int randomNum;
String answer = "";
System.out.println("~ WELCOME! ~");
System.out.println("Can you guess the secret number?");
do {
System.out.print("\nPicking a number between 1-1000........ ");
randomNum = rand.nextInt(1000)+1; //number will be between 1-1000
System.out.println("Done!");
System.out.print("\nGuess the number: ");
guess = input.nextInt();
while(guess<1 || guess>1000) {
System.out.println("\nOut of range! Try again.");
System.out.print("Your guess: ");
guess = input.nextInt();
}
if(guess==randomNum)
System.out.print("You were right!");
else
System.out.println("\nWrong! Better luck next time.");
System.out.println("\nThe secret number was " + randomNum + ".");
System.out.println("Your guess was " + guess + ".");
System.out.print("\nPlay again (yes/no)? ");
answer = input.next();
if(answer.equalsIgnoreCase("no")) {
System.out.print("\nThanks for playing!");
input.close();
System.exit(0);
}
}while(answer.equalsIgnoreCase("yes"));
}
}
I don't think it's really necessary to create another class. Try it out and see what you think!
Related
package w3school;
import java.util.Random;
import java.util.Scanner;
public class nyttprogram {
static void indata() {
{
Scanner determinedNumber = new Scanner(System.in);
int user, computer, number, user2;
System.out.println("Input a number from 0-10");
user = determinedNumber.nextInt();
Random random = new Random();
int randomInt = random.nextInt(10);
if (user == randomInt) {
System.out.println("You guessed the correct number!");
} else {
System.out.println("You guessed the wrong number");
System.out.println("The correct number was: " + randomInt);
}
System.out.println("Input 1 if you want to try again: ");
}
}
public static void main(String[] args) {
indata();
}
}
How do I make the class start over when user input 1 OR if the Class can start over if User inputs wrong number from the start, many thanks
How do I make the class start over when user input 1 OR if the Class can start over if User inputs wrong number from the start, many thanks
The "start over" logic based on some conditions is usually implemented with while and do/while loops.
First let's extract those conditions. We want to iterate again (start over) if:
The user's guess is wrong.
The user's guess is correct, but they input a number different than 1 when asked if they want to continue.
Since we want to run the program at least once, the natural approach would be with a do/while. This will run one iteration, then check against the conditions wanted.
Here's what it looks like:
private static void inData() {
Scanner userInputScanner = new Scanner(System.in);
Random random = new Random();
// Declare the stop/continue condition
boolean isLoopContinue;
do {
// Generate a random number
int expectedNumber = random.nextInt(10);
// Ask the user to guess a number
System.out.println("Input a number from 0-10");
int givenNumber = userInputScanner.nextInt();
if (givenNumber == expectedNumber) {
// Correct answer, check if the user wants to continue
System.out.println("You guessed the correct number!");
System.out.println("\nInput 1 if you want to try again: ");
// If they input "1", then we continue. Else we stop
isLoopContinue = userInputScanner.nextInt() == 1;
} else {
// Wrong answer, loop again
System.out.println("You guessed the wrong number");
System.out.println("The correct number was: " + expectedNumber);
isLoopContinue = true;
}
} while (isLoopContinue);
}
I just wanted to say first that I'm a beginner so I apologize for my (really) horrible code.
I'm creating a program where you input an int and print out the square root using a do while loop. And when you input "0" the program will stop.
How do you stop it?
public static void main(String[] args)
{
Scanner InputNum = new Scanner(System.in);
DecimalFormat formatTenths = new DecimalFormat("0.0");
do {
System.out.println("Please enter an integer.");
int sqroot = InputNum.nextInt();
double Finalsqroot = Math.sqrt(sqroot);
System.out.println("Your Square Root is: " + (formatTenths.format(Finalsqroot)));
} while (sqroot==0);
System.out.println("Closing...");
InputNum.close();
}
}
You need to test if the value entered was 0 (I would test less than or equal to zero, because the square root of a negative number is imaginary). If so, break the loop. Like,
int sqroot = InputNum.nextInt();
if (sqroot <= 0) {
break;
}
try this
public static void main(String[] args) {
Scanner InputNum = new Scanner(System.in);
DecimalFormat formatTenths = new DecimalFormat("0.0");
int sqroot = 0;
do {
System.out.println("Please enter an integer.");
sqroot = InputNum.nextInt();
double Finalsqroot = Math.sqrt(sqroot);
System.out.println("Your Square Root is: " + (formatTenths.format(Finalsqroot)));
} while (sqroot != 0);
System.out.println("Closing...");
InputNum.close();
}
I just initialize sqroot outside of your while and change == to !=
This academic exercise may demand use of a do/while loop, but if you're not constrained to using it, a for loop would also work:
public static void main(String[] args)
{
Scanner InputNum = new Scanner(System.in);
DecimalFormat formatTenths = new DecimalFormat("0.0");
System.out.println("Please enter an integer.");
for(int sqroot = InputNum.nextInt(); sqroot > 0; sqroot = InputNum.nextInt()) {
double Finalsqroot = Math.sqrt(sqroot);
System.out.println("Your Square Root is: " + (formatTenths.format(Finalsqroot)));
}
System.out.println("Closing...");
InputNum.close();
}
Your program as presented in the question has an intrinsic flaw: you ask for input and then immediately try and do something with it (calc the square root) without determining if it is suitable to use.
Switching to a for loop is one way this can be overcome, because it encourages a program flow of "ask for input", "check if input is acceptable", "use input", "repeat"
If you're constrained to using a do/while loop then you still need to follow this flow, which Elliott Frish addresses in his answer, recommending you add in the "check if input is acceptable" part as a dual purpose test of whether the input is <= 0.. Such values are not acceptable for a square root op, and you also want to end the program when you encounter them, so the test can be used to achieve both goals
Side trivia, for loops can be used pretty much exclusively:
for(;;) //same as while(true)
for(;test;) //same as while(test)
for(bool do = true; do; do = test) //same as do..while(test)
..though using while or do is probably more readable than using a for loop for the same job
Note, your while(sqroot==0) is a bug.. you don't want to continue looping while the user entered 0, you want to continue looping while they DIDN'T enter a 0...
I am writing a number-guessing game for my Computer Science 1100 class, one part of which is to print the number of attempts the player takes at guessing the target number. I've defined a variable tries to track that; the program increments it by one every time the player makes a guess.
The game restarts after the player guesses the number correctly, and at that point I want to reset the tries counter. I can't figure out how to do that, however, because the program increments tries each time the number is guessed. How can I do it?
import java.util.Scanner;
import java.util.Random;
public class Q2 {
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
Random r = new Random();
System.out.println("Welcome to the Number Guessing Game");
int x=0;//defining x for later
int tries = 1;//defining tries for later
while (x!=-1) {
int y = r.nextInt(101);//defining random number 0-100
System.out.print("Guess a number between 0 and 100 or enter -1 to quit: ");
x=kbd.nextInt();//redefining x
x=kbd.nextInt();//redefining x
for (int i=1;x!=-1&&x!=y;i=1) {//for loop
if (x<-1||x>100) {//illegal condition
System.out.print("Out of bounds. Try again: ");
}
else if (x>y) {//input greater than random condition
System.out.print("The number is lower. Try again: ");
}
else if (y>x) {//random greater than input condition
System.out.print("The number is higher. Try again: ");
}
x = kbd.nextInt();//redefining x
tries+=i;//defining pattern for tries
}
if (x==y) {//input=random condition
System.out.println("Congratulations! You guessed the number in " + tries + " tries");
}
}
if (x==-1) {//quit condition
System.out.print("Thank you for playing the game!!");
}
}
}
a) Change the scope of your variable
Variables are only available in the scope they are defined in. For example
while (something) { // all code inside the loop is in an inner scope
int variable = 42;
// variable is accessible here
}
// variable is not accessible here
This means, every time the while-loop performs one iteration, variable is newly created. It is a good practice to only define variables in the scope they actually have a meaning (in this case in the while-loop).
b) Assign the variable every time anew
Another way would be to reset the variable each time it is necessary. This would result in such a design:
int variable; // variable is defined outside the inner scope
while (something) {
variable = 42;
// some code that changes variable's value
}
One possible solution would be to encapsulate your guessing game into it's own method, which will re-initialize all variables when called, and create an if condition inside of your loop if the guess is correct.
private static void guessingGame() {
Scanner scanner = new Scanner(System.in);
double randomNum = Math.random();
double tries = 0, guess = 0;
do while (!(guess == randomNum) {
System.in("What is your guess? ");
guess = scanner.nextDouble();
tries++;
if (guess == randomNum) {
System.out.println("Guessed correctly in " + tries + " tries.");
tries = 0;
}
}
}
public static void main() {
guessingGame();
}
I'm writing some Java code that'll make a guessing game, where a random number is generated based on your maximum value and you have to guess the correct number. You can also set the amount of attempts you can get. This is where the problem occurs.You see, you can set a number of attempts in number form or write out "unlimited". I have an example of the code that does this here with comments to help you out:
import java.util.Scanner;
public class Game{
public static int processMaxAttempts;
public static Scanner maxAttempts;
public static String processMaxAttempts2;
public static void main(String args[]){
//Prints out text
System.out.println("Fill in your maximum attempts OR write \"unlimited\".");
//Creates a scanner
maxAttempts = new Scanner(System.in);
//Looks at the scanner "maxAttempts" and reads its integer value
processMaxAttempts = maxAttempts.nextInt();
//Looks at the scanner "maxAttempts" and reads its string value
processMaxAttempts2 = maxAttempts.nextLine();
//Prints out "unlimited" if "maxAttempts" has a string value and "set" if it has an integer value
if(processMaxAttempts2.equals("unlimited")){
System.out.println("unlimited");
}else{
System.out.println("set");
}//Close else
}//Close main method
}//Close class
What happens is a get an error that says this:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:857)
at java.util.Scanner.next(Scanner.java:1478)
at java.util.Scanner.nextInt(Scanner.java:2108)
at java.util.Scanner.nextInt(Scanner.java:2067)
at com.pixelparkour.windows.MainGameWindow.main(MainGameWindow.java:34)
That error targets this line of code:
processMaxAttempts = maxAttempts.nextInt();
So... yeah. I have no idea. I'm very new to Java (I've been learning it for only 3 days) and I'm a bit helpless. I'd love to know what my problem is so I can apply to it the future and program some cool games!
You need to put a check on content type before reading the content.
What you need is :
if(maxAttempts.hasNextInt()){ // this will check if there is an integer to read from scanner
processMaxAttempts = maxAttempts.nextInt();
} else {
processMaxAttempts2 = maxAttempts.nextLine();
}
if(processMaxAttempts2!=null && processMaxAttempts2.equals("unlimited")){
System.out.println("unlimited");
}else{
System.out.println("set");
}
I think this is what you are looking for
public class Test
{
private int guessableNumber;
private Integer maxAttempts;
public Test()
{
maxAttempts = 0;
}
public void doYourStuff(){
Scanner scan = new Scanner(System.in);
Random random = new Random();
System.out.println("Please enter your amount of guesses or type unlimited for unlimited guesses");
String s = scan.next();
if(s.toUpperCase().equals("UNLIMITED")){
guessableNumber = random.nextInt(100);
}
else {
try{
maxAttempts = Integer.parseInt(s);
guessableNumber = random.nextInt(100) + Integer.parseInt(s);
}catch(Exception e){
System.out.println("You did not enter a valid number for max attempts");
}
}
int counter = 0;
System.out.println("Type in a guess");
while(scan.nextInt() != guessableNumber && counter <=maxAttempts){
System.out.println("You did not guess correctly try again");
++counter;
}
if(counter > maxAttempts){
System.out.println("You have exceeded your max attempts");
}
else {
System.out.println("Correct you guessed the correct number: "+ guessableNumber);
}
}
public static void main(String[] args)
{
Test test = new Test();
test.doYourStuff();
}
}
One little trick that always works for me is just going ahead and making a second scanner, i.e. num and text, that way you can always have one looking for int values and the other dealing with the Strings.
I recently started programming with java and need help.
Using Programming Java for Dummies, I'm trying to make a game where a user has to guess a number. The amount of attempts are recorded and displayed once the user finally gets the answer right.
The starred line is giving me trouble, any help?
import static java.lang.System.out;
import java.util.Scanner;
import java.util.Random;
import javax.swing.JOptionPane;
public class HelloWorld
{
public static void main(String args[])
{
Scanner keyboard = new Scanner (System.in);
out.println("Hello, welcome to the Guessing Game.");
out.println("To begin, pick a random number from 1 - 10: ");
int inputNumber = keyboard.nextInt();
int randomNumber = new Random(1).nextInt(10);
int numGuesses = 0;
while (inputNumber != randomNumber){
out.println();
out.println("You're guess was wrong, try again.");
out.println("Pick an integer from 1-10.");
**int inputNumber = keyboard.nextInt();**
numGuesses++;
}
{
out.println("You won in " + numGuesses + " guesses.");
out.println("Thanks for playing!");
}
}
}
Replace
**int inputNumber = keyboard.nextInt();**
with
inputNumber = keyboard.nextInt();
With the original version, you are creating a new variable within the scope of the while, rather than assign to the old variable outside.
Since it is destroyed after the while block, the condition itself uses the variable in functions scope.
This line is redeclaring inputNumber, which has already been declared.
int inputNumber = keyboard.nextInt();
change it to
inputNumber = keyboard.nextInt();
You already defined at the top so you dont have to redefine it. Instead it should be inputNumber = keyboard.nextInt();