public static void main(String[] args) throws IOException {
System.out.println("Hello, come and play a game with me!");
int x = 5;
int guess;
do {
System.out.println("Please input a number...");
guess = System.in.read();
guess = System.in.read();
if (guess < 5) {
System.out.println("You guessed the number!");
break;
}
} while (guess > 5);
}
So here I wrote some code. It's supposed to be a guessing game, but no matter what I input, it always gives me in the output "Please input a number..." NO MATTER WHAT I PUT. Basically, if the "guess" is more than 5, then they guessed the number. If it's not, then they haven't guessed the number. That's the premise of the game. Can someone help me fix my code, so it doesn't just output the same thing regardless?
System.in.read(); gives you char. so when you enter "1", it gives you its char value, 49. so you can not enter integer 5 with typing numbers. so change your reading method. you can use Scanner
You are doing the opposite - an answer less than 5 is accepted as correct.
Here is a working version of your code.
As mentioned in previous answers, the System.in reads in characters so you cannot read in numbers directly. Below The code is leveraging the BufferedReader API whitch works on an InputStream.
public class App {
public static void main(String[] args) throws IOException {
System.out.println("Hello, come and play a game with me!");
int x = 5;
int guess;
do
{
System.out.println("Please input a number...");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
guess = Integer.parseInt(br.readLine());
if(guess < 5){
System.out.println("You guessed the number!");
break;
}
} while(guess>5);
}
}
it looks like you did not use the variable x, try using the Scanner class to get input from the user
public static void main(String[] args) throws IOException {
System.out.println("Hello, come and play a game with me!");
int guess;
Scanner input = new Scanner(System.in);
do {
System.out.println("Please input a number...");
guess = input.nextInt();
if (guess < 5) {
System.out.println("You guessed the number!");
break;
}
} while (guess > 5);
}
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();
}
}
So I started working on a project involving the game MasterMind. I am now completely lost and have no idea what to do next to complete the game. I do not want in run as an applet, just in the console area. BTW this is run on eclipse. I am also having a problem with my if statement. It tells me that the operands are incompatible. The error code is: Incompatible operand types Scanner and Int[].
package masterMind;
import java.util.Scanner;
public class MasterMind {
public static void main(String[] args) {
System.out.println("This is MasterMind, a logic game");
System.out.println("To win you must guess correctly where each number is(The Numbers Range from 1-4)");
System.out.println("You will be told if you get one correct");
System.out.println("You will only get 10 tries, then you lose");
System.out.println("Lets begin");
//Declare Array
int [] answerArray;
answerArray= new int [4];
//Initialize Array
//Change these value to change the answers needed to win
answerArray[0]=2;
answerArray[1]=3;
answerArray[2]=2;
answerArray[3]=2;
//Create Board
System.out.println("__ __ __ __");
Scanner userGuess = new Scanner(System.in);
int num = userGuess.nextInt();
boolean guessedAll = false;
int guessedCount=0;
int tryCounter=0;
while(tryCounter<9 || !guessedAll){
if (userGuess==answerArray) {
} else {
}
//if number equals one of the numbers above then guessedCount++ ...
//if guessedCount==4 then guessedAll=true
tryCounter++;
}
}
}
inside your if statement, you would need 4 if statements, each checking that the number at that spot is guessed correctly. If they are, then display that number, else let them guess again (suggesting a while loop to check if they guessed enough times, or they got it all right.
in order to understand how your input looks after every turn, try to implement a loop...
public static void main(String[] args) {
Scanner userGuess = new Scanner(System.in);
boolean gameRunning = true;
while (gameRunning) {
// getting a line from the input
System.out.println("\ninput a line");
String inputLine = userGuess.nextLine();
System.out.println("the line is: " + inputLine);
// getting an integer
System.out.println("\ninput an integer");
int inputInt = userGuess.nextInt(); // this will give you an int from the input
userGuess.nextLine();
System.out.println("the integer is: " + inputInt);
}
}
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.
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();
}