I need to add a method to my guessing game that i made a while ago. The method should return the value they enter but should use a loop to require re-entry until one of those two values has been specified.
Also if the user inputs a word and not an int, it should ask for a number. I know that I will need to use a string instead of an int. I'm just having trouble figuring this out. Here is what I have so far:
import java.util.Random;
import java.util.Scanner;
class GuessNumber {
static Random rand = new Random();
static Scanner scan = new Scanner(System.in);
static int number;
public static void main(String[] args) {
playGame();
}
public static void playGame() {
number = rand.nextInt(100) + 1;
System.out.println("Guess the number between 1 and 100");
while (true) {
int guess = scan.nextInt();
if (guess < number) {
System.out.println("Higher!");
} else if (guess > number) {
System.out.println("Lower!");
} else if (guess == number) {
System.out.println("Correct!");
Scanner scan2 = new Scanner(System.in);
System.out.println("do you wanna play again?[Y/N]");
String val = scan2.next();
if (val.equalsIgnoreCase("Y")) {
playGame();
} else {
break;
}
}
}
}
}
There might be a better way to do it but try something along the lines of:
String input = scan.next();
int guess;
try{
guess = Integer.parseInt(input);
//rest of the code inside while(true) loop
}
catch(Exception e){
System.out.println("You need to enter a valid number.");
}
and then for the Y/N validation:
String val = "No";
Scanner scan2 = new Scanner(System.in);
do{
System.out.println("do you wanna play again?[Y/N]");
val = scan2.next();
}
while(!val.equalsIgnoreCase("Y") && !val.equalsIgnoreCase("N"))
if (val.equalsIgnoreCase("Y")) {
playGame();
break;
} else {
break;
}
Reasoning: You will get an error if they do not enter a valid number so you need to catch the error and let them know what is wrong. I like to get input as string and try to convert it to integers. As for the do/while section... Unless they enter Y or N it will keep asking them. Once out of the loop, if the input was "Y" it will call the playGame() again and then break after it finishes (basically whenever the user types n in the next game). If it wasn't "Y" then it had to be "N" and needs to break.
Let me know if this helps. I have the full code that will work but this should be easy enough for you to implement.
When you declare your static variables, put:
static int number, guess;
To declare both numbers at the same time. Then, inside the main loop, do the following:
while (true) {
while (true) {
try {
guess = Integer.parseInt(scan.nextLine());
break;
} catch (Exception e) {
System.out.println("Not a valid number!");
continue;
}
}
//Rest of your if's, else if's, etc
}
I've tested it, and it works for me.
If you need me to I can paste in all the code, but you should be able to just nest that second while loop inside the first, before the if statements, easily enough.
Related
I am currently experimenting with Java, trying to get the user to input an integer. If the user doesn't enter an integer I want a message to appear saying "You need to enter an Integer: " with a completely new input field to the original one.
Code:
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner inputScanner = new Scanner(System.in);
int counter = 0;
boolean run = true;
int userInput = 0;
while (run) {
System.out.print("Enter an integer: ");
if (inputScanner.hasNextInt()) {
userInput = inputScanner.nextInt();
} else if (!inputScanner.hasNextInt()) {
while (!inputScanner.hasNextInt()) {
System.out.print("You need to enter an Integer: ");
userInput = inputScanner.nextInt();
}
}
System.out.println(userInput);
if (counter == 6) {
run = false;
}
counter++;
}
}
}
At the moment the code above gives an Exception error ("java.util.InputMismatchException"). I have tried to use a try/catch but this doesn't really work because I want the user to see the second message ("You need to enter an Integer") everytime they don't enter an integer and I don't want it to re-loop around the main run loop for the same reason. I'm sure there is a better way to do this, however I am not sure of it. Any help will be massively appreciated, thanks in advance.
In this case it would make more sense for the Scanner to use hasNextLine and then convert the String to an Integer. If that you could do something like this:
try {
new Integer(inputScanner.hasNextLine);
} catch (Exception e) {
System.out.println(“<error message>”)
}
In place of the if(inputScanner.hasNextInt()) due to the fact that the hasNextInt function will error out if there is not an Integer to be read.
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();
}
}
I'm working on an assignment and I mostly have it finished but I am having an issue with the last method. I'm trying to write a continueGame() method that will ask the user if they want to continue to play, and accept "y" or "n". If answered "y", the program starts again. If answered "n", the program stops and a message is shown. The problem is I need it to trigger the continueGame() method only when userChoice == answer. This is a number guessing game with an object oriented approach.
I've tried to call the continueGame() method inside my else if(userChoice == answer) statement but it doesn't seem to work. Even when my other if/else if statements are triggered, it continues to the continueGame() method.
Here is the main driver for the game
import java.util.Scanner;
public class NumberGame
{
public static void main(String[] args)
{
Scanner input = new Scanner (System.in);
GameOptions opt = new GameOptions(); // Your created class
int userChoice = -1234;
int answer = -1234;
boolean keepPlaying = true;
System.out.println("Guess the Number Game\n");
while (keepPlaying == true) {
answer = (int) (Math.random() * 10)+1;
//Create a getChoice method in your class and make sure it accepts a Scanner argument
userChoice = opt.getChoice(input);
//Create a checkAnswer method in your class. Make sure it accepts two integer arguments and a Scanner argument
opt.checkAnswer(userChoice, answer, input);
// Create a continueGame method in your class and make sure it accepts a Scanner argument
keepPlaying = opt.continueGame(input);
}
System.out.println("Thanks for playing.");
}
}
Here is the class that I am working on for the methods. Note that I can not make any modifications to the main driver file.
import java.util.InputMismatchException;
import java.util.Scanner;
import java.lang.NumberFormatException;
public class GameOptions {
int count = 0;
boolean cont = true;
//getChoice Method for NumberGame
public int getChoice(Scanner scnr) {
System.out.println("Please choose a number between 1 and 10: ");
int userGuess = 0;
String input = scnr.next();
try {
userGuess = Integer.parseInt(input);
if (userGuess < 1 || userGuess > 10) {
throw new IllegalArgumentException("Invalid value. Please enter a number between 1 and 10: ");
}
}
catch(NumberFormatException e) {
System.out.println("Error - Enter Numerical Values Only");
return userGuess;
}
catch (IllegalArgumentException ex) {
System.out.println(ex.getMessage());
}
return Integer.parseInt(input);
}
public void checkAnswer(int userChoice, int answer, Scanner scnr) {
if (userChoice > answer && userChoice < 11) {
System.out.println("Too high. Try again.");
count++;
} else if (userChoice < answer && userChoice > 0) {
System.out.println("Too low. Try again.");
count++;
} else if (userChoice == answer) {
System.out.println("You got it! Number of tries: " + count);
System.out.println("Would you like to play again? (y/n)");
}
}
public static boolean continueGame(Scanner scnr) {
String input = scnr.nextLine();
if (input.toLowerCase().equals("y")){
return true;
} else if (input.toLowerCase().equals("n")){
return false;
} else {
System.out.println("Invalid entry. Please enter either y or n: ");
return continueGame(scnr);
}
}
}
So I should be able to enter a number, and if its lower than the answer it will tell me I am too low, if its higher than the answer it will tell me that its too high, if its equal it will tell me I won and prompt me to press "y" or "n" if I want to continue. Another issue I am running into is that I am getting "Would you like to play again? (y/n)" no matter whether I guess the right number or not and my only option is to hit "y" or "n"
The driver class is calling continueGame() inside the while loop. If you're not allowed to modify that class then presumably asking at every iteration is the intended behaviour.
You should move System.out.println("Would you like to play again? (y/n)"); into the continueGame() method so that it only asks when that method is called.
The way the driver is written (I guess) is coming from your instructor/lecturer/professor, right?
With the driver (as it is), you don't need to call continueGame method from checkAnswer method. The driver is going to call it.
Just run the driver and it will work. If you have a proper IDE (eclipse or Netbeans), trace through and see what the input accepted is (I think there is line-feed in the accepted answer).
Try this (I just changed the loop structure; yours is also valid):
public static boolean continueGame(Scanner scnr) {
while (true) {
String input = scnr.nextLine().trim(); // to remove white spaces and line-feed
if (input.toLowerCase().equals("y")){
return true;
} else if (input.toLowerCase().equals("n")){
return false;
} else {
System.out.println("Invalid entry. Please enter either y or n: ");
}
}
}
Added for checkAnswer method to keep the user guess the answer until he gets correct:
public static checkAnswer(/*three arguments*/) {
boolean correct = false;
while (! correct) {
// accept input
if (answer.equals(input)) {
correct = true;
// print required correct/congrats messages here
} else {
// print required input/try again messages here
}
}
// print would you like to play again with new answer y/n message here.
}
In my opinion, printing "play again with new answer y/n message" should go into continueGame method (from last portion of checkAnswer) method to stick to encapsulation concepts.
I want to make it so that a user entering the wrong data type as figureNumber will see a message from me saying "Please enter an integer" instead of the normal error message, and will be given another chance to enter an integer. I started out trying to use try and catch, but I couldn't get it to work.
Sorry if this is a dumb question. It's my second week of an intro to java class.
import java. util.*;
public class Grades {
public static void main(String args []) {
Scanner stdin = new Scanner(System.in);
System.out.println();
System.out.print(" Please enter an integer: ");
int grade = stdin.nextInt();
method2 ();
if (grade % 2 == 0) {
grade -= 1;
}
for(int i = 1; i <=(grade/2); i++) {
method1 ();
method3 ();
}
}
}
public static void main(String args[]) {
Scanner stdin = new Scanner(System.in);
System.out.println();
System.out.print(" Welcome! Please enter the number of figures for your totem pole: ");
while (!stdin.hasNextInt()) {
System.out.print("That's not a number! Please enter a number: ");
stdin.next();
}
int figureNumber = stdin.nextInt();
eagle();
if (figureNumber % 2 == 0) { //determines if input number of figures is even
figureNumber -= 1;
}
for (int i = 1; i <= (figureNumber / 2); i++) {
whale();
human();
}
}
You need to check the input. The hasNextInt() method is true if the input is an integer. So this while loop asks the user to enter a number until the input is a number. Calling next() method is important because it will remove the previous wrong input from the Scanner.
Scanner stdin = new Scanner(System.in);
try {
int figureNumber = stdin.nextInt();
eagle();
if (figureNumber % 2 == 0) { //determines if input number of figures is even
figureNumber -= 1;
}
for(int i = 1; i <=(figureNumber/2); i++) {
whale();
human();
}
}
catch (InputMismatchException e) {
System.out.print("Input must be an integer");
}
You probably want to do something like this. Don't forget to add import java.util.*; at the beginning of .java file.
You want something in the form:
Ask for input
If input incorrect, say so and go to step 1.
A good choice is:
Integer num = null; // define scope outside the loop
System.out.println("Please enter a number:"); // opening output, done once
do {
String str = scanner.nextLine(); // read anything
if (str.matches("[0-9]+")) // if it's all digits
num = Integer.parseInt(str);
else
System.out.println("That is not a number. Please try again:");
} while (num == null);
// if you get to here, num is a number for sure
A do while is a good choice because you always at least one iteration.
It's important to read the whole line as a String. If you try to read an int and one isn't there the call will explode.
You can actually test the value before you assign it. You don't need to do any matching.
...
int figureNumber = -1;
while (figureNumber < 0) {
System.out.print(" Welcome! Please enter the number of figures for your totem pole: ");
if (stdin.hasNextInt()){
figureNumber = stdin.nextInt(); //will loop again if <0
} else {
std.next(); //discard the token
System.out.println("Hey! That wasn't an integer! Try again!");
}
}
...
Here is my code that I have so far:
import java.util.Scanner;
public class Whatever{
public static void main(String[] args) {
Scanner keyboard = new Scanner (System.in);
System.out.println("How many pigs are there?");
int number = Integer.parseInt( keyboard.nextLine() );
int continueProgram = 0
while(continueProgram == 0)
{
if (number>= 0 && number <= 32767)
{ do this;
continueProgram++;
}else{
do this;
}
I have to use integer.parseInt for the rest of my code to work so I can't change that. Any ways to take only integers rather than letters? My code produces errors because if I input a letter, parseInt will produce red errors rather than output a string like "try again. input numbers please" or something like that.
You need to surround your parse.int with a try catch like this
int number = 0; // you need to initialize your variable first
while (true) {
try {
number = Integer.parseInt(keyboard.nextLine());
break; // this will escape the while loop
} catch (Exception e) {
System.out.println("That is not a number. Try again.");
}
}
Try this one :
Scanner keyboard = new Scanner (System.in);
System.out.println("How many pigs are there?");
if(keyboard.hasNextInt()) {
int number = keyboard.nextInt();
}else{
System.out.println("Not an integer number!");
keyboard.next();
}