In Cannot be resolved and MasterMind - java

Ok, I am having a problem receiving a value... I have been researching for several days, but nothing has hit the topic I need. It is a mastermind game. I am creating this for a Final project in my High School programming class. The Eclipse Compiler is telling me that in cannot be resolved. How do I fix this and Accomplish my goal. This is not being run in an applet.
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");
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");
//Change this value to change the game
int m1=2;
int m2 =3;
int m3=2;
int m4=1;
//Create Board
System.out.println("__ __ __ __");
Scanner UserGuess = new Scanner(System.in);
int num = in.nextInt();
I have very limited Coding knowledge, so please keep it simple and explain

System.in is the InputStream of the system (like the cmd for windows) , in order to read from that you use the Scanner or InputStreamReader just like you are trying to do ... so instead of
in.nextInt();
you need
userGuess.nextInt();
and btw learn to use capital letters properly as it will help you later , like userGuess should not start with a capital since its an instance not a class.
anyways , for your game you have to guess 10 times which means you have to repeat the same guessing action 10 times or till the user guesses all the numbers , thats when you should use a while loop like so ....
boolean guessedAll = false;
int guessedCount=0;
int tryCounter=0;
while(tryCounter<9 || !guessedAll){
//read the number from the user and test it ...
//if number equals one of the numbers above then guessedCount++ ...
//if guessedCount==4 then guessedAll=true
tryCounter++;
}
now i almost gave you all of the algorithm needed to do that homework , but i ain't going to solve it for you till you try , else you will learn nothing ;)
you could ofcourse ask for help as comment after you've tried some ... good luck

for nextInt method you should call it from Scanner object
Change this
int num = in.nextInt();
To
int num = UserGuess.nextInt();

You never closed the brackets when you started the class nor when you started the main method. Match every { with a }.
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");
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");
//Change this value to change the game
int m1=2;
int m2 =3;
int m3=2;
int m4=1;
//Create Board By randomly generating the number
//After generating the code, print the blank board to start the game
System.out.println("__ __ __ __");
//Take in the user's guess (limit is 10)
int limit = 10
for(int i = 0; i < limit; ++i) {
Scanner UserGuess = new Scanner(System.in);
int num = in.nextInt();
//Other logic..Leaving it for you to attempt
}
}
You want to make a program which the user must guess where each number is in a 4 digit code.. Well how do you do this?
We need the user to be able to input a number, typically the rules of this game are:
There are 6 possible numbers or colors
The code is 4 numbers or colors long
The user has ten tries to guess the code correctly
That means we have to start by doing something like this.
Generate the 4-digit code somehow (with the possible combinations from 0000-6666) and the split the random number put it in an array
Ask the user to enter a number guess along with a position for that number
Keep checking the user guess against the code, each time display the current guesses and which ones they have correct

Related

How to use while loop user input established variable out of scope (if possible)

I need to ask the user for a number of dice to roll, (at least 1) and then loop if necessary to return a positive integer. Simple question, but I'm new to Java and don't understand how to do this using a while loop and bringing my variable back into scope.
Here's what I have so far, as anyone can see my variable 'numOfDice' is never pulled back into scope, as I need it later in my program to establish a variable array length.
while (true) {
System.out.println("Hello! How many dice would you like to roll");
int numOfDice = scan.nextInt();
if (numOfDice<=0) {
System.out.println("Please enter a positive integer and try again");
}else {
break;
}
}
So as you can see my variable is never pulled back into scope, and I've tried initializing it before the while loop, with no luck. I've also tried
System.out.println("Hello! How many dice would you like to roll");
int numOfDice = scan.nextInt();
while (true) {
if (numOfDice<=0) {
System.out.println("Please enter a positive integer and try again");
}else {
break;
}
}
But this results in an infinite loop if a negative number is an input, as my if will repeat forever.
Anyways, I'm very new to Java (my 6th week learning) and any veteran help would be much appreciated. I'm willing to learn new ways to create these loops or tricks to pull variables back into scope (if possible).
Solved. Thanks to tgdavies telling me to split the declaration and assignment I was able to finish this problem. Here's the solution for anyone who stumbles upon this.
System.out.println("Hello! How many dice would you like to roll");
int numOfDice;
numOfDice = scan.nextInt();
while (true) {
if (numOfDice <= 0) {
System.out.println("Please enter a positive integer and try again");
numOfDice = scan.nextInt();
} else {
break;
}
}
This is very simple.
First you have to declare your variable outside the loop.
int numOfDice = -1;
Then you need to think of a way to update the state of your variable numOfDice inside the loop. Hence,
numOfDice = sc.nextInt();
Should be inside your loop. Now, the state of your variable numOfDice is updated. After that we can check if the value is a negative or not, and reiterate the loop accordingly.
Hence, the overall code will look like this.
int numOfDice = -1; //Declaration - value is negative because the while loop has to be executed at least once.
Scanner sc = new Scanner(System.in);
while(numOfDice<=0){ // checks if the variable is negative or positive, loop continues if the value is negative
System.out.println("Hello! How many dice would you like to roll");
numOfDice = sc.nextInt(); //updates the state of the variable
if (numOfDice<=0) {
// this line will be printed only if the value is negative.
System.out.println("Please enter a positive integer and try again");
}
}
Hope this answer is helpful.
Refer this article to understand more about while loops in java.
Let me start by showing my solution first...
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Let's start rolling some dice");
while (true) {
System.out.println("Hello! How many dice would you like to roll");
int numOfDice = scan.nextInt();
if (numOfDice < 0) {
System.err.println("Please enter a positive integer and try again");
} else if (numOfDice == 0) {
System.out.println("Goodbye!");
break;
}
}
scan.close();
}
As you can see, it is not much of a variation, but it has clear boundaries. For example, you can't have a negative number of dice rolled. So checking for the number of dice to be less than zero (negative) is an error and an appropriate message is shown when that condition is reached.
The second thing you see is a clear case for ending the "forever" loop. And that is when zero is passed through the Scanner object. Not much of an explanation required. Pass zero and simply break out of the loop.
The rest, if a positive integer is passed, keep rolling the dice!
Output sample
Let's start rolling some dice
Hello! How many dice would you like to roll
2
Hello! How many dice would you like to roll
3
Hello! How many dice would you like to roll
9
Hello! How many dice would you like to roll
-3
Please enter a positive integer and try again
Hello! How many dice would you like to roll
-2
Please enter a positive integer and try again
Hello! How many dice would you like to roll
1
Hello! How many dice would you like to roll
3
Hello! How many dice would you like to roll
0
Goodbye!
...to return a positive integer
Sorry for the dramatic heading, but I miss this from the OPs question the first time I read it. The code above keeps rolling until the user enters zero. Let's modify this so that it returns a positive integer.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Let's start rolling some dice");
while (true) {
System.out.println("Hello! How many dice would you like to roll");
int numOfDice = scan.nextInt();
if (numOfDice < 0) {
System.err.println("Please enter a positive integer and try again");
} else if (numOfDice == 0) {
System.out.println("Goodbye!");
break;
} else {
// Add some code here (i.e. a Random generation of dice values 1-6)
System.out.println("You rolled a " + diceRollValue);
break;
}
}
scan.close();
}
Variable Scope
Since the OP seems to struggle with issues related to scope, I will expand on this answer to focus on scope. Good coding practices call for minimizing the scope of variables. This means (in theory):
No global variables, period!
Local variables should be declared at the lowest possible block.
Variables shall be declared as close to the point of usage as possible.
Of course, in practice, global variables are often necessary. But what no developer should do is declare global variables by default. Instead, all variables shall be declared at the lowest levels of the code, and then "bubbled up" as needed and stop "bubbling" them up when the desired accessibility is reached. Let's look at an example from this code.
The variable numOfDice is declared inside the while loop. This is the lowest level where this variable can be declared. Since the variable is used at the top of the loop, it is OK to declare it and assign a value in the same line. The question is, should this variable be declared outside the loop? The answer is yes, for a very specific reason.
Creating a "forever" loop while(true){...} may not be a good idea. IN FACT, it can be argued that putting the break condition there might be a better coding practice than to include the break condition inside the loop. So, for this reason (and improving readability of the code as well), we might be better off setting the the variable outside the loop to a value, and then prompt the user to enter the number of rolls inside the loop like this:
System.out.println("Let's start rolling some dice");
int numOfDice = -1;
while (numOfDice != 0) {
System.out.println("Hello! How many dice would you like to roll");
int numOfDice = scan.nextInt();
...
}
Setting the value to -1 allows the instruction pointer to enter the loop because the evaluation of numOfDice returns true. Once inside the loop, it will continue to iterate until the evaluation returns false; and this is when the user enters 0. In the original code, negative values prompt an error message. Negative and positive values continue the "game". This is perfectly fine. As to the improved readability, when you see while (numOfDice != 0) the intent is clear; much better than to "hide" the break condition inside the loop. If the loop contain a lot of lines of code, the break condition is harder to find. So, in the end, this is a better solution.
An alternative is to use a do...while loop. This is the preferred structure when the intent is for the loop to run at least once. This is possible because the break condition is evaluated at the end of the loop rather than at the beginning in a conventional while loop. The equivalent do...while loop is as follows:
System.out.println("Let's start rolling some dice");
int numOfDice = 0; // initialize to the break condition value (just in case)
do {
System.out.println("Hello! How many dice would you like to roll");
int numOfDice = scan.nextInt();
...
} while (numOfDice != 0);
The last thing with regards to scope. I mentioned before that variables should be declared as close to the point of usage as possible. This means that instead of this
public void myMethod() {
int myVariable = 0
.
.
.
.
.
myVariable = someCodeThatSetsValue();
.
.
}
You should do this instead to follow best practices
public void myMethod() {
.
.
.
.
.
.
int myVariable = someCodeThatSetsValue();
.
.
}

Introducing an array to store scores in Java

The question I am working on is:
Write a program that:
asks the user how many exam scores there are (and verifies that the user entered a positive integer), prompt the user for each real-valued score, one by one (as shown below in Sample program behavior / output: box), Calculate and output the average of the scores and count and output how many scores are greater than the average (as shown below in Sample program behavior / output: box).
Sample program behavior / output:
How many exams scores do you have to enter? 5
Enter score #1: 95.0
Enter score #2: 92.0
Enter score #3: 68.0
Enter score #4: 72.0
Enter score #5: 70.0
The average score is: 79.4
There are 2 scores larger than the average.
This is my code:
import java.util.Scanner;
public class testee {
public static void main(String[] args) {
int examnum = -1;
Scanner scan = new Scanner (System.in);
while (examnum<0) {
System.out.println("How many exam scores do you have to enter?");
examnum = scan.nextInt( );
}
for (int i=1; i<=examnum; i++) {
System.out.println("Enter score #" + i + ": ");
for (int a=1; a<=i; a++) {
a = scan.nextInt();
}
}
}
}
What I did produces the following output however my problem is that I need to store the scores that are input to later compute an average so inside my for loop I would need to store the scores as an array but I do not know how to approach that.
First prompt looks good however there is one small problem.
Hint: What condition would you use for your while loop if you wanted to ensure that the value entered was not less than 1 since zero would be rather non-productive?
It's always nice to inform the User of any invalid entry.
To place items into an Array you need to declare that array and initialize it to the proper size:
int[] scoresArray = new int[examnum];
Think about this, where do you think this line of code should be placed?
Hint: You need to ensure that the required array size is already properly established.
Why use two for loops when you can use only one? What can the second (inner nested) for loop do that the outer for loop just simply can't do?
Hint: Nothing! "Enter score #" + (i+1) + ": ". Of course in this case i (within the initialization section) would need to start from 0 and always be less than examnum (within the termination section).
If you want to add an element to your array, where do you think would be a great place in your code to do that?
Hint: int score = scan.nextInt(); scoresArray[i] = score;.
Things to consider:
When scores are being entered, do you think the User entries should be validated? What if the User enters one or more (or all) alpha characters instead of digits in any of your prompts that require an Integer value? Do you end up getting an InputMismatchException? How would you handle such a thing?
Yes, you can nest while loops within a for loop and visa-versa.

Writing a loop that will repeat itself "N" times as decided by the user

I need to write a program for Java that "rolls" two 6-sided die and that keeps track of how many tries it took to roll a 7. The program also needs to run this process N number of times, determined by the user. After the Nth trial, the program needs to compute the average amount of trials it takes to roll a 7.
I'm pretty confident that I should use a while loop inside of a for loop but I'm unsure of exactly how to do it. I already have written the code to a program that "rolls the dice," and is shown below.
import java.util.*;
public class RollDice {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
Random rand = new Random();
String input = "";
do {
System.out.println("Rolling the dice...");
System.out.println("You rolled a"+((rand.nextInt(6)+1)+(rand.nextInt(6)+1)));
System.out.println("Roll again? (y/n)");
input = keyboard.next();
} while (input.equalsIgnoreCase("y"));
}
}
Yes, I know it's a do-while loop, but it's all I have so far.
https://codereview.stackexchange.com/questions/31980/a-simple-dice-roll-game
This would be a great place for you to start. Then just add a second die, and a variable for the average. But please do not copy this code directly. Use it as a template/guideline. I want no part in plagiarism.

Issue with do-while loop

Please note that I while I am comfortable with Java, I am not exceptionally gifted nor do I know all the jargon, so please explain your answers with very little coder jargon and as much normal English, or explain what the jargon means after you use it. Also, this is my first time with Stackoverflow, so let me know if this was a decent question and give me some pointers.
I am taking an AP Computer Science class at my high school. We use Java. We were recently taught do-while loops and I just completed the "lab" that uses do-while loops, however, there is an issue.
Firstly, let me explain the lab. The program generates a random integer between 1-10 which the user must guess (guess is stored as an int using a scanner), there are a few integer values which track number of guesses, how many guesses were greater than the computer integer, and how many were too low. When you look at my code, you will notice that I have a System.out.println(compGen);//compGen is the computer generated int. The purpose was to test the code.
The issue is in the if-statement that compares userGen (user guess) and compGen.
if(userGen==compGen)
{
//do a lot of stuff
}
In this if-statement, it is not printing the correct SOPs that I have written IF the user guesses more than once. HOWEVER, I did not write this into the program, it seems to do it on its own. I used the SOP I mentioned early where the compGen int is printed, and I typed that in as my first guess and it worked perfectly. Everything in the if-statement block executed perfectly and printed everything correctly. However, when I did it as my second guess, third guess, or any guess that was not the first one, NOTHING was printed. See code below and run it. I don't believe this should make a difference, but the IDE that I use is Eclipse, hence the package statement. Please help.
package Chapter_3.Lab03_Chapter3;
import java.util.*;
public class Guess
{
public static void main(String[] args)
{
Scanner userInput = new Scanner(System.in);//Scanner
int compGen = (int)(Math.random()* 10 + 1);//compGen is computer number
System.out.println(compGen); //USED TO VERIFY FAILURE. VALUE WAS ENTERED TO TEST CODE
int guessTrack = 0;//tracks number of guesses
int tooHighTrack = 0;//CREATING INTS TO TRACK STUFF
int tooLowTrack = 0;
System.out.println("Welcome to the integer guessing game that everyoone loves!");//PROMPT
System.out.println("Please enter your guess for the integer. Remeber, it is between one and ten.");//GREETING
int userGen = userInput.nextInt();//USER GUESS
do
{
guessTrack++;//Increase guess value
if(userGen > compGen)//checks user value in relation to computer generated int
{
System.out.println("Try again! Your guess was too high!");//inform user of bad guess
userGen = userInput.nextInt();//new guess
tooHighTrack++;//if guess is too high, this int tracker increases
}
else if(userGen < compGen)//checks user value in relation to computer generated int
{
System.out.println("Try again! Your guess was too low!");//inform user of guess
userGen = userInput.nextInt();//new guess
tooLowTrack++;//increases if user guess is too low
}
else if(userGen==compGen)//if both values are equivalent, execute THIS IS THE PROBLEM STATEMENT!!
{
System.out.println("Great job! You guessed the right number!");//congratulate
if(guessTrack>1)
{
System.out.println("It took you: "+guessTrack+" guess to get the right answer.");//print guess tracked int
}
else
{
System.out.println("It took you: "+guessTrack+" guesses to get the right answer.");//print guess tracked int
}
System.out.println(tooHighTrack +" guesses were too high and "+ tooLowTrack+ " were too low.");//print how many guess were too big or too low
System.out.println("HELLO"); //Used to verify failure of code
userInput.close();//close scanner object
}
}
while (userGen != compGen);//condition to be ultimately checked
}
}
I haven't been able to figure out what is wrong. At one point I deleted the entire if-statement and re-typed it (I knew it wouldn't do anything, but I had to try). This issue makes no sense to me. There are no errors or anything that pop up, nothing pops up on the console which scares me a little. Thanks in advance.
First off, a lot of text you put here. Maybe try to minimize the problem next time as a suggestion ;) Otherwise everything is fine
To your problem. Let me minimize your code and then explain to you, what happens.
1. The Code
int val = scanner.nextInt();
do {
if (val < 5) {
// too low
val = scanner.nextInt();
} else if (val > 5) {
// too high
val = scanner.nextInt();
} else {
// correct
// THIS CODE DOESN'T RUN?!
}
} while (val != 5);
2. What does your code do?
You read your first number before your loop. That's fine. Then, you enter an if-elseif-else statement. Note, that once inside one of those blocks, the other blocks won't get executed. Now the problem is, that you read your next user inputs inside of the if-elseif! The program reads the next value and leaves the whole if-elseif-else. Your code does not execute, because the loop then ends before the next iteration, therefore the correct user input is not going through the if-elseif-else at all.
3. The solution
Remove all nextInt() reads and just have one as the first thing inside the loop:
int val;
do {
val = scanner.nextInt();
if (val < 5) {
// too low
} else if (val > 5) {
// too high
} else {
// correct
// THIS CODE RUNS NOW!
}
} while (val != 5);
Such things, structures that need to do something at least once before checking the loop condition, are usually done with do while loops rather than while loops
You are setting user input during the loop, and it is then checked afterwards. Try moving the body of the else if(userGen==compGen) block to after the loop like this:
public static void main(String[] args)
{
Scanner userInput = new Scanner(System.in);//Scanner
int compGen = (int)(Math.random()* 10 + 1);//compGen is computer number
System.out.println(compGen); //USED TO VERIFY FAILURE. VALUE WAS ENTERED TO TEST CODE
int guessTrack = 0;//tracks number of guesses
int tooHighTrack = 0;//CREATING INTS TO TRACK STUFF
int tooLowTrack = 0;
System.out.println("Welcome to the integer guessing game that everyoone loves!");//PROMPT
System.out.println("Please enter your guess for the integer. Remeber, it is between one and ten.");//GREETING
int userGen = userInput.nextInt();//USER GUESS
do
{
guessTrack++;//Increase guess value
if(userGen > compGen)//checks user value in relation to computer generated int
{
System.out.println("Try again! Your guess was too high!");//inform user of bad guess
userGen = userInput.nextInt();//new guess
tooHighTrack++;//if guess is too high, this int tracker increases
}
else if(userGen < compGen)//checks user value in relation to computer generated int
{
System.out.println("Try again! Your guess was too low!");//inform user of guess
userGen = userInput.nextInt();//new guess
tooLowTrack++;//increases if user guess is too low
}
}
while (userGen != compGen);//condition to be ultimately checked
//The numbers have matched since it exited the loop.
System.out.println("Great job! You guessed the right number!");//congratulate
if(guessTrack>1)
{
System.out.println("It took you: "+guessTrack+" guess to get the right answer.");//print guess tracked int
}
else
{
System.out.println("It took you: "+guessTrack+" guesses to get the right answer.");//print guess tracked int
}
System.out.println(tooHighTrack +" guesses were too high and "+ tooLowTrack+ " were too low.");//print how many guess were too big or too low
System.out.println("HELLO"); //Used to verify failure of code
userInput.close();//close scanner object
}
The while condition is checked as soon as the program reaches the end of the code inside the loop. So suppose they enter the wrong number; the program says it's too low or too high, and then asks for another number:
userGen = userInput.nextInt();//new guess
Now suppose this new number is the correct one. The program finishes your if statement, then gets to the end of the loop. Then, at that point, userGen is equal to compGen. So the while condition fails, and the program exits the loop immediately, without ever getting to the code that prints the results.
One way to solve it would be to move the logic for userGen == compGen, that prints the results, outside the loop--that is, after the end of the loop. That way, it will be executed whenever the loop is exited. Note that when you exit the loop, we know that userGen == compGen, because if it weren't, the loop would go back.
Let's say the computer generated number was 3, and you guess 5.
5>3, so the if(userGen > compGen) statement executes:
System.out.println("Try again! Your guess was too high!");//inform user of bad guess
userGen = userInput.nextInt();//new guess
tooHighTrack++;//if guess is too high, this int tracker increases
you print the message, get a new guess, then increment your counter... but when you get the new guess, say it was the correct answer 3, userGen is now equal to CompGen (both are 3) and now the
while condition is evaluated:
while (userGen != compGen)
this is now false because userGen == compGen (both are 3). Your code never gets a chance
to print the correct message because the loop exits before it can happen. hope that helps
Your userGen is not being checked after every user input.
The problem is that you have your check inside an else-if block, which will check the end of the while statement before it loops back through again.
If you change
else if(userGen==compGen)
to
if(userGen==compGen)
then because it is not apart of the if-else block, it will be checked after every input (before the while condition is checked)
Alternatively you could move your user-input to the start of the do-while block like so:
package Chapter_3.Lab03_Chapter3;
import java.util.*;
public class Guess
{
public static void main(String[] args)
{
Scanner userInput = new Scanner(System.in);//Scanner
int compGen = (int)(Math.random()* 10 + 1);//compGen is computer number
System.out.println(compGen); //USED TO VERIFY FAILURE. VALUE WAS ENTERED TO TEST CODE
int guessTrack = 0;//tracks number of guesses
int tooHighTrack = 0;//CREATING INTS TO TRACK STUFF
int tooLowTrack = 0;
System.out.println("Welcome to the integer guessing game that everyoone loves!");//PROMPT
System.out.println("Please enter your guess for the integer. Remeber, it is between one and ten.");//GREETING
int userGen = -1;//USER GUESS
do
{
userGen = userInput.nextInt();
guessTrack++;//Increase guess value
if(userGen > compGen)//checks user value in relation to computer generated int
{
System.out.println("Try again! Your guess was too high!");//inform user of bad guess
userGen = userInput.nextInt();//new guess
tooHighTrack++;//if guess is too high, this int tracker increases
}
else if(userGen < compGen)//checks user value in relation to computer generated int
{
System.out.println("Try again! Your guess was too low!");//inform user of guess
userGen = userInput.nextInt();//new guess
tooLowTrack++;//increases if user guess is too low
}
else if(userGen==compGen)//if both values are equivalent, execute THIS IS THE PROBLEM STATEMENT!!
{
System.out.println("Great job! You guessed the right number!");//congratulate
if(guessTrack>1)
{
System.out.println("It took you: "+guessTrack+" guess to get the right answer.");//print guess tracked int
}
else
{
System.out.println("It took you: "+guessTrack+" guesses to get the right answer.");//print guess tracked int
}
System.out.println(tooHighTrack +" guesses were too high and "+ tooLowTrack+ " were too low.");//print how many guess were too big or too low
System.out.println("HELLO"); //Used to verify failure of code
userInput.close();//close scanner object
}
}
while (userGen != compGen);//condition to be ultimately checked
}
}
This will cause your if-else block to be checked everytime a user inputs data before the conditions for the do-while are checked.

Having a few problems after recently starting Eclipse Java

Hello I have start learning Java coding on Eclipse recently and have only made a few very simple things.
I am trying to make a basic game where a random number from 1-100 is chosen by the program and you have to try and pick it, with the program telling you whether you are higher or lower. However I've encountered a few problems.
import java.util.Scanner;
import java.util.*;
public class numbergame {
/**Number guessing game
* calculates a random number and has the player guess it
*/
public static void main (String[] args) {
int myNumber, guess;
System.out.println("What is your guess?");
Scanner guessScanner = new Scanner(System.in);
Random myNumber = new Random();
int number = randomNumber.nextInt(100);
guess = guessScanner;
if (guess<myNumber) {
System.out.println ("The Number is less");
}
if (guess>myNumber) {
System.out.println ("Your guess is more");
}
else{
if (guess==myNumber)
System.out.println ("Your number is correct");
}
}
}
This is what I have done so far,
The following lines are not working but I am not sure how to fix them:
Random myNumber = new Random();
int number = randomNumber.nextInt(100);
guess = guessScanner;
if (guess<myNumber) {
Could I please have some advice as of how to fix these? And how to make the program record then umber of guesses?
change
guess = guessScanner
to
guess = guessScanner.nextInt();
You are willing to take the user input as int. But guess = guessScanner from this you are assigning int to Scanner. That is wrong.
And also change as
Random randomNumber = new Random();
You are trying to assign Scanner to an int:
guess = guessScanner;
Instead, you should call the nextInt() method on it, to get the integer the user inputed:
guess = guessScanner.nextInt();

Categories