I’m trying to use Data that I saw from another post Creating a console menu for user to make a selection to create a menu in which the user selects an option. When I go to run my program it throws several errors.
Maybe I’m not importing it correctly but this is the only method
I can think of.
import java.util.Random;
import java.util.Data;
public class Main{
public static void main(String[] args) {
System.out.println("Please enter 1 if you'd like to guess the computer's number or enter 2 to have the computer guess your number. If 2, please enter a number between 1-100 after you enter 2. ");
Data data = new Data();
data.menu();
Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt();
switch (choice) {
case 1:
double r = (Math.random()*((100-1)+1))+min;
int win = 0;
while (win != 1);
System.out.println("The computer has guessed a number, please make a guess. ");
int u1 = scanner.nextInt();
if (r > u1)
System.out.println("Too low.");
else if (r < u1)
System.out.println("Too high.");
else if (r == u1){
System.out.println("You guessed it!!!!!!! Congratulations!!!!!!!!!!");
int win = win + 1 ;}
else
System.out.println();
break;
case 2:
System.out.println("You'd like myself, the computer to guess huh, well be prepared to get destroyed!");
int un = scanner.nextInt();
if (un == 36){
System.out.println("Chandler I told you not to!!!!!!");
break;}
else
System.out.println();
System.out.println("Your number is " + un);
break;
default:
System.out.println("You weren't supposed to do that!!!! Stop the program and run it again. Congrats! You broke it! Chandler, if you entered 36, ");
TimeUnit.SECONDS.sleep(5);
System.out.print("you've been banned!");
}
}
}
All your compiler errors in order.
import java.util.Data; // Does not exist, #MadProgrammer is correct, causes error
Data data = new Data(); // Error, Data cannot be resolved as to a type
Scanner scanner = new Scanner(System.in); // You did not import java.util.Scanner.
// Scanner cannot be resolved to a type.
double r = (Math.random()*((100-1)+1))+min; // min cannot be resolved to a variable
// You didn't define it
System.out.println("The computer has guessed a number, please make a guess. ");
int win = win + 1 ;} // win was a variable that was previously defined. Just change it
from "int win =" to "win = "
TimeUnit.SECONDS.sleep(5); // Did you mean to import java.util.concurrent.TimeUnit;
Also, if you want to "ban" someone from your program, then why not make a .txt file to read from, that helps your program remember if it has been "broken" before.
Related
I've created many different types of method in my coding as my task requires to, so I faced some problems that I'm trying to incorporate loops that allow only 3 guesses from the user. After each round, the user has the option of whether to continue playing or to stop. How should I implement that? Also, any mistakes in my coding? Thank you in advanced!
import java.util.Random;
import java.util.Scanner;
public class GuessmyGame{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
Random random = new Random();
int number = random.nextInt(100)+1;
printInstruction();
int guess = in.nextInt();
guessNum(number, guess);
numberOfTries(guessNum);
}
public static void printInstruction(){
System.out.println(" I am thinking of a number between 1 and 100.");
System.out.println(" Can you guess what it is? ");
System.out.println(" Type a number : ");
}
public static void guessNum(int number, int guess){
if (number == guess){
System.out.println("Congratulations! You got it right.");
}
else if(number > guess){
System.out.println("Your guess is too low.");
Scanner in = new Scanner(System.in);
guess = in.nextInt();
System.out.println("Your guess is: "+guess);
guessNum(number, guess);
}
else{
System.out.println( "Your guess is too high.");
Scanner in = new Scanner(System.in);
guess = in.nextInt();
System.out.println("Your guess is: "+guess);
guessNum(number, guess);
}
}
public static void numberOfTries(int guessNum){
Random random = new Random();
int number = random.nextInt(100)+1;
for(int i = 0; i < 3; i++){
System.out.println("Out of guesses!");
System.out.println("The number was " + number);
}
}
}
Use a while loop and add a boolean condition.. let's call it canContinue. You'll also need to keep track of how many times the user has attempted to guess, let's say it's called attemptCount as well as the correctness of the user's latest guess (correctGuess).
When attemptCount is 3 or correctGuess is true, prompt the user if they want to continue. If their answer suggests they don't want to continue, set canContinue to false, which causes the exit the loop and complete. Otherwise, reset attemptCount (to 0 presumably to allow another 3 attempts). The code that follows highlights the requested logic. since it's clear the code provided in the question has many bugs.
var promptToRetry = false;
while (canContinue) {
if (correctGuess) {
// Let user know their guess was correct
promptToRetry = true;
}
if (attemptCount > 2) {
// Let user know they didn't get the right number
promptToRetry = true;
}
if (promptToRetry) {
boolean wantsToTryAgain = PromptUserToTryAgain(); //Code returning bool which prompts user if they want to try again (need to implement)
if (wantsToTryAgain) {
attemptCount = 0; //Resets attempt counter
correctGuess = false; //Resets the guess
promptToRetry = false;
} else {
canContinue = false; //Causes loop to exit
}
}
...
}
}
I'm looking to repeat a "game" if it is already satisfied in my case where user has to guess the random number. I can't understand where to to get back to the main game unless i have to create another "do - while" loop inside it and retype the game again in the section where it says: System.out.println("you have tried: " + count + " times. Would you like to play again? y/n"). Is there a way to just bring back to the actual guess loop rather than create another one?
Hopefully makes sense.
import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;
public class pass {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String pass = "password123";
String input;
int guess;
int count;
count = 0;
int num;
do {
System.out.print("Enter your password: ");
input = scanner.next();
} while (!input.equals(pass));
System.out.println("Correct! Now play the guess game! Guess a number between 1 - 10.");
do {
num = ThreadLocalRandom.current().nextInt(1,10);
guess = scanner.nextInt();
count++;
if (guess == num) {
System.out.println(" Well done!");
**System.out.println("you have tried: " + count + " times. Would you like to play again? y/n");**
}
else if (guess < num) {
System.out.println("your number is smaller than the number given");
}
else {
System.out.println("your guess is too high");
}
} while (guess != num);
}
}
The simplest solution would be to move the entire "guess loop" into a separate method. Then in the case when you want it to repeat, just call the method recursively.
If you want to reuse code you can make functions (or methods here, because we are inside a class). They can be used to encapsulate code and call it from anywhere to use it.
You can define a methods like that:
public static void methodName() {
// code go here
}
Then, you can call it from anywhere like that :
pass.methodName(); // It will execute the code inside methodName()
In reality, this is a lot more complex than that, you can give methods values and return others, change the scope of it to make it internal only or reachable by other classes. But I presume that you are a beginner so I keep it simple. I strongly recommend you to make a quick research about Object Oriented Programmation!
For your code, you can put the game's while loop in a method and call it at the beginning and each time the player wants to restart the game. Good luck with your game!
I manage to do this way. It seems working but one thing is letting me down at the very last when I key in "n" or other key than "y". Exception in thread "main" java.util.InputMismatchException. Is there a more softer way to finish it?
import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;
public class pass {
public static void randomnum(){
Scanner scanner = new Scanner(System.in);
int guess;
int count;
count = 0;
int num;
do {
num = ThreadLocalRandom.current().nextInt(1,10);
guess = scanner.nextInt();
count++;
if (guess == num) {
System.out.println(" Well done!");
System.out.println("you have tried: " + count + " times.");
String answer;
do{
System.out.println("Do you want to play again? y/n");
answer = scanner.next();
if (answer.equals("y")) {
System.out.println("let's play again");
randomnum();
System.out.println("Correct! Now play the guess game! Guess a number between 1 - 10.");
}
else {
System.out.println("you are logout!");
break;
}
}while (answer.equals("Y"));
randomnum();
}
else if (guess < num) {
System.out.println("your number is smaller than the number given");
}
else {
System.out.println("your guess is too high");
}
} while (guess != num);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String pass = "password123";
String input;
do {
System.out.print("Enter your password: ");
input = scanner.next();
} while (!input.equals(pass));
System.out.println("Correct! Now play the guess game! Guess a number between 1 - 10.");
randomnum();
}
}
So for my Java programming class one of the assesments is the following (a classic number guessing game):
Write a program that plays the HiLo guessing game with
numbers. The program should pick a random number between 11 (inclusive) and 88 (exclusive), then
repeatedly prompt the user to guess the number. On each guess, report to the user that he or she is
correct or that the guess is high or low. Continue accepting guesses until the user guesses correctly or
choose to quit. Use a sentinel value to determine whether the user wants to quit. Count the number of
guesses and report that value when the user guesses correctly. At the end of each game (by quitting or
a correct guess), prompt to determine whether the user wants to play again. Continue playing games
until the user chooses to stop. You are required to utilise at least a while loop and a for loop correctly.
So far, the game is fully working, using WHILE and IF functions. But in order to get full marks on my solution, it requires me to use at least one FOR loop, but I'm struggling to do that.
import java.util.*;
public class Guessing {
public static void main (String[] args)
{
//Setting up the variables
final int MAX = 88;
final int MIN = 11;
int answer, guess = 1;
String another="Y";
//Intializing scanner and random
Scanner scan = new Scanner (System.in);
Random generator = new Random();
//play again loop
while (another.equalsIgnoreCase("Y"))
{
//Generate a random number between 11 and 88
answer = generator.nextInt(MAX-MIN)+11;
System.out.print ("Guess the number I picked between "+MIN+" and "
+ MAX + "!\n");
while(guess!=answer)
{
System.out.println("Enter your guess: ");
guess = scan.nextInt();
System.out.println(answer);
if (guess<answer && guess != 0)
System.out.println("Your guess was too low! (0 to exit) ");
else if (guess>answer)
System.out.println("Your guess was too high!(0 to exit) ");
else if (guess==0){
System.out.println("You excited the current round.");
break;}
else{
System.out.println("Your guess was correct!");
break;}
}
}
//Asking player to play another game
System.out.println("Do you want to play another game?(Y|N)");
another = scan.next();
if (another.equalsIgnoreCase("N"))
System.out.println("Goodbye, thank you for playing");
}
}
}
So far, the program works. It correctly gives higher/lower advice, the current round stops when typing in 0 as a guess and you can start another round with Y/N. But Im struggling to substitute one of the functions/loops with a FOR loop.
You can substitute the central while loop with a for loop that you can also use to count the number of iterations
for(int i=0;;i++)
{
System.out.println("Enter your guess: ");
guess = scan.nextInt();
System.out.println(answer);
if (guess<answer && guess != 0)
System.out.println("Your guess was too low! (0 to exit) ");
else if (guess>answer)
System.out.println("Your guess was too high!(0 to exit) ");
else if (guess==0){
System.out.println("You excited the current round.");
break;}
else{
System.out.println("Your guess was correct!\n");
System.out.println("It took "+i+" guesses to get the answer");
break;}
}
}
This for loop is an infinite loop because it hasn't got the second argument. However your program will exit the for loop when the correct answer is given because of the break in the final else.
As the number of guesses is counted upwards, one may use the for loop on that.
Normally one would write for (int i = 0; i < n; ++i) { but here we want to know the loop counter after the for loop and have to declare it before:
int numberOfGuesses = 0;
for (; guess != 0 && guess != answer; numberOfGuesses++) {
}
... numberOfGuesses
There is no upper limit other than finding the answer or quiting.
All three parts in for (PARTA; PARTB; PARTC) are optional.
I really need help with this. Im using BlueJ and it says 'might not be initialized'. How do i fix it? its correctNumber roughly line 16ish.
import java.util.Scanner;
import java.util.Random;
public class NumberGuessingGame {
public static void main(String[] args) {
Random randomNumber = new Random();
int correctNumber;
int guessTracker;
int guessLimit = 6; //the number of tries
int userInput;
Scanner in = new Scanner(System.in);
int game = 1;
boolean winTracker = false;
while (1 == game)
correctNumber = randomNumber.nextInt(1100); //computer generates a random number, max 100
userInput = 0;
guessTracker = 0;
System.out.println("Hello and welcome to this number guessing game. Please guess the number between 1 and 100 and I will help you by telling you if your guess is too high or low: ");
while (**correctNumber** != userInput && guessTracker < guessLimit){
userInput = in.nextInt();
guessTracker++;
if (userInput == correctNumber){
System.out.println("You have won the game! Your reward is a fact game: Did you know the first working camera was invented in 1816! "); //winner message, with a unlocked fact game
System.out.println("The correct number was " + correctNumber); //the correct number
System.out.println("It took a total of " + guessTracker + " guesses"); //number of guesses it took the user to guess the right number.
}
else if (userInput < correctNumber){
System.out.println("Your number is too low"); //displays that the users guess is too low
System.out.println("Please enter your next guess: "); //// user can now eneter their next guess
}
else if (userInput > correctNumber){
System.out.println("Your number is too high"); //displays that the users guess is too high
System.out.println("Please enter your next guess: "); // user can now eneter their next guess
}
if (correctNumber != userInput){
System.out.println("Sorry you have run out of guesses! The correct number was: " + correctNumber); // displays the correct number
}
}
}
}
You need to initialize correctNumber to a value.
This is not always the case, but think about this:
you call while(1 == game) which then initialized correctNumber to a random number, correctNumber = randomNumber.nextInt(1100) this would initialize correctNumber, but when the java compiler compiles your application it can't be sure that 1 == game is true. Therefore, when the compiler gets to the next loop while (**correctNumber** != userInput && guessTracker < guessLimit) your compiler sees that correctNumber has not been initialized even though it would be by the first loop.
In short, the compiler does not know whether a loop will be entered or not, therefore user3437460 is absoultely correct in saying that you need to initialize local scope variables, in this case int correctNumber = 0 will work perfectly for you.
I really need help with this. Im using BlueJ and it says 'might not be initialized'. How do i fix it?
Local scope variables need to be initialized (assigned an initial value) before use:
int correctNumber = 0
Same applies for your other variables.
I am trying to make a program which can accept certain integer type input from user, but stop the input as soon the user enters "stop".
I have tried doing so, but it's not working properly. Have a look.
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.io.*;
class Iron {
public static void main(String args[]) throws InterruptedException {
Scanner in = new Scanner(System.in);
System.out.println("Do you wanna play?, type yes to start.");
String a = in.nextLine();
String b; String c="goo";
String d,e="helloWorld";
String al="helloworld";
int f=0,g;
if (a.equalsIgnoreCase("yes")) {
System.out.println("Thanks for staring the game ");
TimeUnit.SECONDS.sleep(1);
System.out.println("-------Welcome to Need For Fun-------");
System.out.println();
TimeUnit.SECONDS.sleep(1);
while (!c.equalsIgnoreCase("yes")) {
System.out.println();
System.out.println("Enter your name_");
b = in.nextLine();
System.out.println("Is your name " + b + "?");
System.out.println("If yes type yes or if not type something else");
c = in.nextLine();
}
TimeUnit.SECONDS.sleep(0);
System.out.println("So, the game is quite similar to hand cricket");
System.out.println("You will win, if your number and Computer's number are equal");
System.out.println("To stop the game any time type start");
System.out.println();
TimeUnit.SECONDS.sleep(1);
System.out.println("So ready to play the game?, type yes to confirm.");
d = in.nextLine();
if(d.equalsIgnoreCase("yes"));
{
while(!al.equalsIgnoreCase("stop")) {
System.out.println();
try {
System.out.println("Type your number");
e = in.nextLine();
f = Integer.parseInt(e);
}
catch(NumberFormatException e1) {
al = in.nextLine();
if(al.equalsIgnoreCase("stop"))
break;
}
if (f < 10) {
g = (int) (Math.random() * 10);
if (f == g)
System.out.println("Congrats, you won. ");
else
System.out.println("Oops!, try again");
} else if (f>10)
System.out.println("Please enter a number between 1-10");
}
System.out.println("Thanks for playing, better luck next Time");
}
}
}
}
It does stops when I type stop, but I need to enter it two times.
Here's the run tab where I executed my program.
Do you wanna play?, type yes to start.
yes
Thanks for staring the game
-------Welcome to Need For Fun-------
Enter your name_
gourav
Is your name gourav?
If yes type yes or if not type something else
yes
So, the game is quite similar to had cricket
You will win, if your number and Computer's number are equal
To stop the game any time type start
So ready to play the game?, type yes to confirm.
yes
Type your number
4
Oops!, try again
Type your number
54
Please enter a number between 1-10
Type your number
4
Oops!, try again
Type your number
stop
3
Oops!, try again
Type your number
stop
stop
Process finished with exit code 0
change this block
catch(NumberFormatException e1) {
al = in.nextLine();
if(al.equalsIgnoreCase("stop"))
break;
}
to
catch(NumberFormatException e1) {
if(e.equalsIgnoreCase("stop"))
break;
}