MasterMind Game-Java - java

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);
}
}

Related

Why is my code outputting "tryAgain cannot be resolved to a variable" in the context of a do-while loop?

I'm new to Java and I'm trying to add a way to loop an if-else statement by asking the user if they want to try again at the end of the program, which I have attempted with a do-while loop. However, when compiling the program it outputs a java error stating that tryAgain cannot be resolved to a variable. Any help would be appreciated.
import java.util.Scanner;
public class Simple{
public static void main(String[] Args){
Scanner againScanner = new Scanner(System.in);
Scanner numberScanner = new Scanner(System.in);
do{
System.out.println("Please type an integer and I will determine whether it is odd or even.");
int number = numberScanner.nextInt();
if(number % 2 == 0){
System.out.println(number + " is an even number.");
}
else{
System.out.println(number + " is an odd number.");
}
numberScanner.close();
}
while (tryAgain = true);
System.out.println("Would you like to try again (type True or False)?");
Boolean tryAgain = againScanner.nextBoolean();
againScanner.close();
}
}
First of all, I must point out that the compilation of the java language is sequential, you must define before using any property or variable, and your tryAgain must be defined before using it.
Second, in java, any variable defined in the body of a loop is called a local variable, and it cannot be referenced by global code, so your code must be modified like this:
public class Simple{
public static void main(String[] Args){
Scanner againScanner = new Scanner(System.in);
Scanner numberScanner = new Scanner(System.in);
Boolean tryAgain=true;
do{
System.out.println("Please type an integer and I will determine whether it is odd or even.");
int number = numberScanner.nextInt();
if(number % 2 == 0){
System.out.println(number + " is an even number.");
}
else{
System.out.println(number + " is an odd number.");
}
System.out.println("Would you like to try again (type True or False)?");
tryAgain= againScanner.nextBoolean();
}
while (tryAgain);
againScanner.close();
numberScanner.close();
}
}

"Guess My Number" game with only allow 3 guesses from user

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
}
}
...
}
}

Java scanner input loop throwing No Such Element exception after first loop

I want a program that repeatedly prompts the user to input a number and then prints whether that number is prime or not. This works once, then on the next iteration it gives a No Such Element Exception before the user can enter another input.
I've tried using IF statements with hasNext() or hasNextInt() but those never seem to be true for the same reason. I also tried using a FOR loop to iterate a fixed number of times but that gives the same error. Why is this allowing for user input the first time it loops through but not after that?
public static void primeChecker()
{
Scanner scan = new Scanner(System.in);
System.out.print("Please enter a number: ");
int number = scan.nextInt();
if (isPrime(number)) {
System.out.println(number + " is prime");
}
else {
System.out.println(number + " is not prime");
}
scan.close();
}
public static void main(String[] args)
{
int y=1;
while(y!=0)
{
primeChecker();
}
Remove scan.close();, as it is closing the scanner.
In order to repeatedly ask the user for a number without stopping, you need to put a while around the code.
Here is my take on this challenge:
public static void primeChecker() {
while(true) {
Scanner scan = new Scanner(System.in);
System.out.print("Please enter a number: ");
int number = scan.nextInt();
if (isPrime(number)) {
System.out.println(number + " is prime");
} else {
System.out.println(number + " is not prime");
}
}
}
public static void main(String[] args) {
primeChecker();
}
This code should repeatedly ask you for a number(after telling you what the previous answer was). It worked for me!
First of all what does your local variable have to do with the function? even if you pass it to function it won't change.
by looking at your code one thing you can do is safely remove y it has nothing to with it, and check in prime checker if number is equal to 0 System.exit(), this is one way to do it without changing much of this code.
while (true) {
primeChecker();
}
and inside primeChecker
int number = scanner.nextInt();
if (number == 0) {
System.exit(0);
}
it will terminate the programme when input is 0.
here you can learn more about System.exit:- https://www.baeldung.com/java-system-exit

How to keep the program running if the user entered Y?

Here is my code:
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner Keyboard = new Scanner(System.in);
{
System.out.println("What is the answer to the following problem?");
Generator randomNum = new Generator();
int first = randomNum.num1();
int second = randomNum.num2();
int result = first + second;
System.out.println(first + " + " + second + " =");
int total = Keyboard.nextInt();
if (result != total) {
System.out.println("Sorry, wrong answer. The correct answer is " + result);
System.out.print("DO you to continue y/n: ");
} else {
System.out.println("That is correct!");
System.out.print("DO you to continue y/n: ");
}
}
}
}
I'm trying to keep the program to continue but if the user enters y and closes if he enters n.
I know that I should use a while loop but don't know where should I start the loop.
You can use a loop for example :
Scanner scan = new Scanner(System.in);
String condition;
do {
//...Your code
condition = scan.nextLine();
} while (condition.equalsIgnoreCase("Y"));
That is a good attempt. Just add a simple while loop and facilitate user input after you ask if they want to continue or not:
import java.util.*;
class Main
{
public static void main(String [] args)
{
//The boolean variable will store if program needs to continue.
boolean cont = true;
Scanner Keyboard = new Scanner(System.in);
// The while loop will keep the program running unless the boolean
// variable is changed to false.
while (cont) {
//Code
if (result != total) {
System.out.println("Sorry, wrong answer. The correct answer is " + result);
System.out.print("DO you to continue y/n: ");
// This gets the user input after the question posed above.
String choice = Keyboard.next();
// This sets the boolean variable to false so that program
// ends
if(choice.equalsIgnoreCase("n")){
cont = false;
}
} else {
System.out.println("That is correct!");
System.out.print("DO you to continue y/n: ");
// This gets the user input after the question posed above.
String choice = Keyboard.next();
// This sets the boolean variable to false so that program
// ends
if(choice.equalsIgnoreCase("n")){
cont = false;
}
}
}
}
}
You may also read up on other kinds to loop and try implementing this code in other ways: Control Flow Statements.

Conditionals and Loops evenOdd

I am trying to read an integer from the user, then print even if that number is an even number or odd otherwise. I have been told I can assume that the user types a valid integer. The input/output should match the following example:
Type a number: 14
even
What am I missing? Any ideas on how I can get the desired inputs and expected outputs? Test1[3][Test4]4
import java.util.Scanner;
public class evenOdd {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
int even = scan.nextInt();
int odd = scan.nextInt();
if ((even%2)==0){
System.out.println("Type a number:"+ even);
}
else {
System.out.println("Type a number:"+ odd);
}
}
}
The problem is that you have all your variables and order of the flow of your program mixed up. In English this is what you are doing
Prompt user for an integer, call that integer "even"
Prompt user for an integer, call that integer "odd"
If the integer called "even" is divisible by 2 without a remainder then print "type a number" and then the value of the integer called "even"
Otherwise print "type a number" and then the value of the integer called "odd"
You only need to read a value from the user once, then decide which message to print based on that value:
import java.util.Scanner;
public class evenOdd {
public static void main(String[] args) {
System.out.println("Type a number:");
Scanner scan = new Scanner(System.in);
int number = scan.nextInt();
if ((number%2)==0){
System.out.println("even");
}
else {
System.out.println("odd");
}
}
}
I have pointed out some issues in your code. Please correct them.
import java.util.Scanner;
//follow java naming convention and name class as "EvenOdd"
public class evenOdd {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int number = scan.nextInt(); //renamed to number
int odd = scan.nextInt(); //do not need this variable
if ((number %2)==0){
System.out.println("Even");
}
else {
System.out.println("Odd");
}
}
}
Ask the user the question first so that he knows he has to input a number
System.out.println("Type a number: ");
You can simply just get 1 input from the user and store on the same variable
int input = scan.nextInt();
Then you would just check that 1 input with the if/else and display the correct output
if ((input%2)==0){
System.out.println(input + " is even.");
}
else {
System.out.println(input + " is odd.");
}

Categories