Hi I'm making a game where the player is met with a robot and the robot asks it to guess a number between 1-10. The player has three tries or they die. I've written all my code and the guessing works fine but whenever the play gets it right he still dies. I added a couple of print statements to see what value my code was returning and it seems to be returning the wrong value. Can someone help me out? Thanks.
Goes from this class
if (choice != -1) {
if (john[choice] != null) {
if (john[choice].compPlayerAttack()) {
System.out.print("IT'S GAME OVER MAN!\n");
System.exit(0);
}
else {
System.out.println("Robot appears. Guess a number between 1-10. Get it right and you can pass, or you die. You have three chances.\"");
int answer = 0;
john[choice].toPass(answer);
if (answer== 1) {
System.out.println(answer);
map[x][y].removeJohnPlayer();
}
else { System.out.println(answer);
System.out.print("IT'S GAME OVER MAN!\n");
System.exit(0);
}
To this class
public int toPass(int right){
int hiddenNum = numram.nextInt(MAX_NUMBER);
Scanner input = new Scanner(System.in);
int numOfGuesses = 0;
int a = right;
do {
System.out.println("Enter a number by guessing: ");
int guessedNum = input.nextInt();
numOfGuesses++;
if (guessedNum == hiddenNum) {
System.out.println("Darn! Your number is matched. You may live.");
System.out.println("You have made " + numOfGuesses + " attempts to find the number!");
a = 1;
break;
} else if (guessedNum < hiddenNum) {
System.out.println("Try a bigger number");
} else if (guessedNum > hiddenNum) {
System.out.println("Try a smaller number");
}
} while (numOfGuesses < 3);
System.out.println(a);
return a;
}
Here
john[choice].toPass(answer);
you are ignoring the value returned by your toPass method.
Change it to:
answer = john[choice].toPass(answer);
BTW, there's no reason to pass an argument to your toPass method, since it makes no use of it, and it can't change it (since Java is a pass by value language). A return value is enough.
i.e. change your method to public int toPass().
Another change you should make is to change the return type to boolean. Returning true or false is more readable than returning 1 or 0.
Related
There's two things I'm needing help with. Loop issue 1) I have to initialize this variable outside of the loop, which makes the loop fail if the user inputs a string. Is there a way around that? Basically, if I set N to anything then the do-while loop just immediately reads it after getting out of the
import java.util.Scanner;
/**
* Calculates sum between given number
*/
public class PrintSum {
public static void main(String[] args) {
int N = 0;
String word;
boolean okay;
Scanner scan = new Scanner(System.in);
System.out.print("Please enter a number from 1-100: ");
do {
if (scan.hasNextInt()) {
N = scan.nextInt();
} else {
okay = false;
word = scan.next();
System.err.print(word + " is an invalid input. Try again. ");
}
if (N > 100 || N < 1) {
okay = false;
System.err.print("Invalid Input. Try again. ");
} else {
okay = true;
}
} while (!okay);
loop(N, 0);
}
public static void loop(int P, int total) {
while (P >= 1) {
total = total + P;
P--;
}
System.out.println(total);
}
}
If not, then the issue becomes, how do I solve this? I thing that I need to be able to say
if (scan.hasNextInt() || ??? > 100 || ??? < 1) {
okay = false;
word = scan.next();
System.err.print(word + " is an invalid input. Try again. ");
} else {
okay = true;
}
What do I put in the ??? to make this work? I think I just don't know enough syntax.
Thank you!
Why don't you try this?
do {
if (scan.hasNextInt()) {
N = scan.nextInt();
} else {
okay = false;
word = scan.next();
System.err.print(word + " is an invalid input. Try again. ");
continue;
}
if (N > 100 || N < 1) {
okay = false;
System.err.print("Invalid Input. Try again. ");
continue;
} else {
okay = true;
}
} while (!okay);
break is used to end the loop as soon as the user enters the invalid character(condition of the else clause), so the loop doesn't fail.
Looking at your edited question, continue is what you are looking for if you might want to allow the user to enter another value after entering the invalid value.
Use break or continue based on requirement. More on breaks and continue.
Your second approach can be solved as follows:
if (scan.hasNextInt()){
N = scan.nextInt();
if (N > 100 || N < 1) {
System.err.print("Invalid input. Try again. ");
}
//perform some operation with the input
}
else{
System.err.print("Invalid Input. Try again. ");
}
I have a problem validating the program. I have tried using, While/Switch but it is all the same. The issue is when a user enters the wrong input for example 5, it shows the error and then it lets them type it in again, but if they type in the wrong number again, the program does not validate. I can definitely copy the code again and again within it, but there should be an easier way.
I hope you understand what I am trying to achieve.
How could I make it so it is a continues loop?
// Choosing the right room
public static int rooms () {
int room;
// Creating a new keyboard input
Scanner scanner = new Scanner(System.in);
// Displaying a message on the screen
System.out.println("What room are you in? ");
// Input
room = scanner.nextInt();
if (room==1) {
roomOne();
} else if (room==2) {
roomTwo();
} else if (room==3) {
roomThree();
} else if (room==4) {
roomFour();
} else {
System.out.println("Wrong room number, please enter the room number.");
room = scanner.nextInt();
}
//System.out.println("Sorry but you entered the wrong room number " + room + " Enter the correct room number 1-4 ");
return room;
} // End Rooms
You are looking for a while loop, something like this.
I use a do ... while to execute the line at least once.
The methods check the value and print a message if this is not correct. Return false will prevent the code to exit the loop and read again.
{
// Creating a new keyboard input
Scanner scanner = new Scanner(System.in);
int room;
do {
// Displaying a message on the screen
System.out.println("What room are you in? ");
room = scanner.nextInt();
} while( !isValid(room) );
... //if else or switch
}
private boolean isValid(int room){
if(room > 4 || room < 1){
System.out.println("Try again ;)" );
return false;
} else return true;
}
This is a quick code note even test.
while (true) {
int room = scanner.nextInt();
if(room < 1 || room > 4) {
System.out.println("Wrong room number, please enter the room number.");
continue;
}
break;
}
if (room == 1)
roomOne();
else if (room == 2)
roomTwo();
else if (room == 3)
roomThree();
else if (room == 4)
roomFour();
Hope it helps, nevertheless you should read a little more about loops.
This is how you should set up a loop for input cleaning:
Define a boolean value and assign a true or false value
Make the while loop run on the boolean value
When input is "clean", set the boolean value to true
I am trying to develop a simple high low game that asks the user after playing if they would like to play again. If I remove the outer while loop the logic of the inner loop does exactly what I want it to do, however I am unsure how to wrap the inner loop with an outer loop that will ask the play again question and if the answer is yes put them back into the inner loop. Below is my code.
import java.util.Scanner;
import java.util.Random;
public class HiLoGuess {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in); // Creates scanner object.
Random numb = new Random(); // Creates an instance of the random class.
int guess = -1; // Placeholder for users guess.
int answer = numb.nextInt(100)+1; // Generates a random number for the game.
int count = 0; // Placeholder for the guess counter.
int sentinel = 0; // Placeholder for players answer as to whether they want to play again or not.
String newgame = "y";
while (newgame.equalsIgnoreCase("y"))
{
while (guess != sentinel && guess != answer) //Loop that ends when user enters a zero.
{
System.out.println ("Enter a number between 1-100 or 0 to quit");
guess = scan.nextInt();
count++;
if (guess < answer && guess > 0 )
{
System.out.println("Your guess is too low, guess again");
}
else if (guess > answer)
{
System.out.println ("Your guess is to high, guess again");
}
else if (guess == answer)
{
System.out.println ();
System.out.println ("You guessed correctly, you win!!!");
System.out.println ("It took you " + count + " guesses");
}
}
System.out.print();
System.out.println("Play another game: y or n?");
newgame = scan.nextLine();
}
}
}
You need to put these initializations into the outer loop:
int guess = -1;
int answer = numb.nextInt(100)+1;
int count = 0;
Otherwise they keep the value from the last game and the inner loop will not be executed any more.
you never reset your guess, sentinel, or answer variables
so (guess != sentinel && guess != answer) always evaluates to false after the first time the game is played, and therefore the inner while loop never executes after the first game
while (guess != sentinel && guess != answer) //this is false after the first game because you don't reset variables
{ ...}
Update for OP comment:
to get your code to do what you want you need to add the resets between the outter and inner while loop like this
while (newgame.equalsIgnoreCase("y"))
{
guess = -1;
answer = numb.nextInt(100)+1;
count = 0;
while (guess != sentinel && guess != answer) //Loop that ends when user enters a zero.
{ ...}
}
Replace newgame = scan.nextLine(); by this : newgame = scan.next();
And you need to initialise your variables inside your while loop, so that the flag is reseted to false and the random generate new result to guess.
public class Game
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in); // Creates scanner object.
Random numb = new Random(); // Creates an instance of the random class.
String newgame = "y";
while (newgame.equalsIgnoreCase("y")) {
int count = 0; // Placeholder for the guess counter.
int guess = -1; // Placeholder for users guess.
int answer = numb.nextInt(100) + 1; // Generates a random number for the game.
int sentinel = 0; // Placeholder for players answer as to whether they want to play again or not.
while (guess != sentinel && guess != answer) // Loop that ends when user enters a zero.
{
System.out.println("Enter a number between 1-100 or 0 to quit");
guess = scan.nextInt();
count++;
if (guess < answer && guess > 0) {
System.out.println("Your guess is too low, guess again");
} else if (guess > answer) {
System.out.println("Your guess is to high, guess again");
}
else if (guess == answer) {
System.out.println();
System.out.println("You guessed correctly, you win!!!");
System.out.println("It took you " + count + " guesses");
}
}
System.out.println();
System.out.println("Play another game: y or n?");
newgame = scan.next();
}
}
}
I'm new to Java, and I'm working on a method in my program that checks the users input to be within bounds, not a null value (zero), not a letter, and a positive number. So originally I incorporated two while loops within this method to check for the validity of these inputs, but I would like to simplify it in one loop. I'm getting an error when I input a letter (ex. a) after a few inputs, and I believe it is due to the two different while loops making it more complicated. Can someone help me with this please?
public static void valid(String s, int max)
{
while(sc.hasNextInt() == false) {
System.out.println("That is not correct. Try again:");
sc.nextLine();
}
int value;
while((value= sc.nextInt()) > max || (value= sc.nextInt()) <= 0){
System.out.println("That is not correct. Try again: ");
sc.nextLine();
}
sc.nextLine();
return;
}
You have:
int value;
while((value= sc.nextInt()) > max || (value= sc.nextInt()) <= 0){
System.out.println("That is not correct. Try again: ");
sc.nextLine();
}
Which is doing sc.nextInt() twice, so value does not necessarily have the same value in these two cases and it is also asking you for a number twice.
A fix would be something like this:
int value;
while((value = sc.nextInt()) > max || value <= 0) {
System.out.println("That is not correct. Try again: ");
sc.nextLine();
}
which would make it better but you still have issues. If value is bigger than max, then the loop will iterate again calling nextInt() but this time you have not checked for hasNextInt(). This is why you'd better have everything in one loop. Something like this:
public static void valid(String s, int max) {
while(true) {
if(!sc.hasNextInt()) { //this is the same as sc.hasNextInt() == false
System.out.println("That is not correct. Try again:");
sc.nextLine();
continue; //restart the loop again
} else {
int value = sc.nextInt();
if(value > max || value <= 0) {
System.out.println("That is not correct. Try again:");
sc.nextLine();
continue; //restart the loop from the top - important!
} else {
extendedValidation(value, s);
return;
}
}
}
}
Try something more like (pseudo code):
while valid input not yet received:
if input is an integer:
get integer
if in range:
set valid input received
skip rest of line
extended validation
With a little thought, you should be able use one "print error message" statement. But using two could be arguably better; it can tell the user what they did wrong.
What is the purpose of the String s parameter? Should you be checking that instead of a Scanner input?
Also, don't be surprised by mixing nextInt() and nextLine(). -- Source
I prefer using do-while loops for input before validation.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int max = 1000;
int val = -1;
String in;
do {
// Read a string
System.out.print("Enter a number: ");
in = input.nextLine();
// check for a number
try {
val = Integer.parseInt(in);
} catch (NumberFormatException ex) {
// ex.printStackTrace();
System.out.println("That is not correct. Try again.");
continue;
}
// check your bounds
if (val <= 0 || val > max) {
System.out.println("That is not correct. Try again.");
continue;
} else {
break; // exit loop when valid input
}
} while (true);
System.out.println("You entered " + val);
// extendedValidation(value, in);
}
I would say that this is a lot closer to what you're looking for, in simple terms...
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
final int MIN = 0;
final int MAX = 10;
Scanner sc = new Scanner(System.in);
int value = -1;
boolean valid;
do {
valid = sc.hasNextInt();
if (valid) {
value = sc.nextInt();
valid = value > MIN && value < MAX;
}
if (!valid) {
System.out.println("Invalid!");
sc.nextLine();
}
} while (!valid);
System.out.println("Valid Value: " + value);
}
}
You should be able to abstract this code to suit your requirements.
I am creating a simple program using the java language which uses a bunch of similar methods to retrieve information from the user. The method i have used to deal with the user entering invalid data seems very incorrect to me, so i am seeking professional guidance on how to better handle invalid data.
I have attempted to search for similar questions but have found none.
This is a sample of one of my methods:
public static int getInput()
{
int temp = 1;
do
{
System.out.println("Answers must be between 1 and 15");
temp = reader.nextInt();
if(temp >=1 && temp <= 15)
{
return temp;
}
else
{
System.out.println("Please enter a valid value");
}
}while(temp > 15 || temp < 1);
//This value will never be reached because the do while loop structure will not end until a valid return value is determined
return 1;
}//End of getInput method
Is there a better way to write this method?
This question is entirely made up so i can learn a better method to implement in my future programs.
Is using a labeled break statement acceptable? such as:
public static int getInput()
{
int temp = 1;
start:
System.out.println("Answers must be between 1 and 15");
temp = reader.nextInt();
if(temp >=1 && temp <= 15)
{
return temp;
}
else
{
System.out.println("Please enter a valid value");
break start;
}
}
Thank you very much in advance.
You have forgotten to check the case, that non-number values are entered (Scanner#nextInt throws a java.util.InputMismatchException). One suggestion which takes care of that issue, is less redundant and more flexible:
public static int getInput(int min, int max) {
for (;;) {
Scanner scanner = new Scanner(System.in);
System.out.println(String.format("Answers must be between %s and %s", min, max));
try {
int value = scanner.nextInt();
if (min <= value && value <= max) {
return value;
} else {
System.out.println("Please enter a valid value");
}
} catch (InputMismatchException e) {
System.out.println("Input was no number");
}
}
}
If you are just worried about the return that is not used and double checking temp you can do something like
public static int getInput()
{
while(true)
{
System.out.println("Answers must be between 1 and 15");
temp = reader.nextInt();
if(temp >=1 && temp <= 15)
{
return temp;
}
else
{
System.out.println("Please enter a valid value");
}
}
}//End of getInput method