First you have to know that I'm a noob to Java, i just started to code and it's my first programming language. So please don't be angry if I'm begin a bit stupid, I just wanna learn to code - Thanks
I'm trying to make a simple " guessing game ", but my code aren't waiting for the user-input.
please help me, I don't know what to do.
My code:
public static void main(String[] args)
{
//Creating the scanner
#SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
//Creating the two random numbers.
Random rand = new Random();
int userNumber = rand.nextInt(10) + 1;
int comNumber = rand.nextInt(10) + 1;
//Asks the user what to do.
System.out.println("Your number is: " + userNumber +" of 10");
System.out.println("Do you think that your number is Heigher(H), Lower(L) or Equal To(E) the computers number");
//Checking if the user is right.
//If the user types in LOWER
if(userNumber < comNumber && input.equals("L"))
System.out.println("You are right. The computer's number is: " + comNumber);
if(userNumber < comNumber && !input.equals("L"))
System.out.println("You are wrong. The computer's number is: " + comNumber);
//If the user types in EQUAL TO.
if(userNumber == comNumber && input.equals("E"))
System.out.println("You are right. The computer's number is: " + comNumber);
if(userNumber == comNumber && !input.equals("E"))
System.out.println("You are wrong. The computer's number is: " + comNumber);
//If the user types in HEIGHER.
if(userNumber > comNumber && input.equals("H"))
System.out.println("You are right. The computer's number is: " + comNumber);
if(userNumber > comNumber && !input.equals("H"))
System.out.println("You are wrong. The computer's number is: " + comNumber);
else
System.out.println("You can only type in ' L ', ' E ' or ' H '.");
}
}
I would be happy if you could help me out whit my problem, and tell me how I can remove the #SuppressWarnings("resource") / explain why it have to be there.
You're using Scanner wrong. You need to call scanner.nextLine() to get input (a String) from the user, and you need to convert the String to an integer (with Integer.parseInt) to compare it with other ints.
You're going to have to import java.util.Scanner into your project. Take a look at this link that will give you plenty of information about it.
Edit: Just noticed you had it at the top. The next thing you should do is create a variable, say "guess" of type string, and you want to assign input.next() to that variable. Then you can replace the input.equals() functions with the guess.equals() function.
http://www.homeandlearn.co.uk/java/user_input.html
You should import java.util.*;
And You aren't taking any input from user, try
int inp=input.nextInt();
To answer your original question, you are getting an error because you aren't importing java.util.Scanner
import java.util.Scanner;
To address some of the other issues:
You are not reading in anything from the user. You use the Scanner methods to do this.
String guess = input.nextLine() is what I would use.
Secondly, your if statements would not work the way you are using them. This may not be the most compact but it is good for readability.
if(guess.equals("L")){
if(userNumber < comNumber){
System.out.println("You are right. The computer's number is: " + comNumber);
} else {
System.out.println("You are wrong. The computer's number is: " + comNumber);
}
} else if(guess.equals("E")){
if(userNumber == comNumber){
System.out.println("You are right. The computer's number is: " + comNumber);
} else {
System.out.println("You are wrong. The computer's number is: " + comNumber);
}
} else if(guess.equals("H")){
if(userNumber > comNumber){
System.out.println("You are right. The computer's number is: " + comNumber);
} else {
System.out.println("You are wrong. The computer's number is: " + comNumber);
}
} else {
System.out.println("You can only type in ' L ', ' E ' or ' H '.");
}
I also suggest closing the Scanner as good practice at the end. input.close()
You might want to read the documentation of the Scanner class. It has some examples on how to use it properly.
The main problem is in your if statements: With input.equals("L") you are asking if the scanner object is equal to the string "L", which is impossible, since they aren't the same type.
To get a string from the input stream you could use input.next() and compare that to "L". Remember though to only call it once before all the ifs, otherwise the programm waits for a new input at every condition check.
Regarding the warning:
As you can read in the documentation, Scanner needs to be closed with input.close() after use.
And just as a hint, never use the #SuppressWarnings annotation if you don't know what your are suppressing. It is meant as a tool for you to use when you know that something the compiler warns you about cannot happen.
In this case it tried to warn you about a resource leak, which is absolutely correct.
EDIT:
Just as an idea how you could improve your design. You could do something similar to:
String expectedInput;
if (userNumber < comNumber) {
expectedInput = "L";
} else if (userNumber == comNumber) {
expectedInput = "E";
} else {
expectedInput = "H";
}
String userInput = input.next();
if (userInput.equals(expectedInput)) {
System.out.println("You are right. The computer's number is: " + comNumber);
} else {
System.out.println("You are wrong. The computer's number is: " + comNumber);
}
You would still have to check for wrong input though.
This has a more natural flow to the logic and is easier to read.
Another advantage would be that you are separating two different concepts: finding out who had the higher number and finding out if the user guessed right. This might seem like a little thing now, but things like the seperation of concepts and levels of abstraction will become more important the more complex your software gets.
Just had another idea. You could even get rid of the code duplication in the last bit and add a check for wrong input like this:
String userInput = input.next();
boolean isInputValid = Arrays.asList("L", "E", "H").contains(userInput);
if (isInputValid) {
String rightWrong = userInput.equals(expectedInput) ? "right" : "wrong";
System.out.println("You are " + rightWrong + ". The computer's number is: " + comNumber);
} else {
System.out.println("You can only type in ' L ', ' E ' or ' H '.");
}
Though it is debatable if using a ternary operator is good style...
Related
I've looked around and can't seem to find an answer as to what exactly the problem is. It executes fine up until the loop and then it seems to ignore the loop and gets hung up so I am rather confused.
package classGame;
import java.util.*;
public class GameTwo {
static int randomNumber;
static int numOfGuess = 5;
static Scanner GameTwo = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Frank: Hello there! My name is Frank. This is the introduction to the game.");
System.out.print("Frank: Please tell me what you would like to be called: ");
if(GameTwo.hasNextLine()) {
String userName =GameTwo.nextLine();
System.out.println(userName + ": My name is: " + userName);
System.out.println("Frank: Well " + userName + ", it's nice to meet you. ");
System.out.println("Frank: Lets play a little game, I want you to guess a number, It's already" +
" in my head and it's between 1-10.");
int guessResult = 1;
int randomGuess = 0;
while(guessResult != -1) {
randomGuess = GameTwo.nextInt();
guessResult = checkGuess(randomGuess);
}
while (randomGuess != guessResult) {
System.out.println(userName + ":Is the number: ");
randomGuess = GameTwo.nextInt();
if(randomGuess < 1 || randomGuess > 10 || randomGuess > guessResult || randomGuess < guessResult) {
System.out.println("Frank: Thats not right "+ userName);
} else if (randomGuess == guessResult) {
System.out.println("Frank: Hey...Thats pretty good...You got it!");
}
}
}
}
public static int getRandomNum () {
randomNumber = (int) (Math.random()*10);
return randomNumber;
}
public static int checkGuess(int guess) {
if(guess == randomNumber) {
return -1;
} else {
return guess;
}
}
}
here is what it prints out up to the loop
Frank: Hello there! My name is Frank. This is the introduction to the game.
Frank: Please tell me what you would like to be called: T
T: My name is: T
Frank: Well T, it's nice to meet you.
Frank: Lets play a little game, I want you to guess a number, It's already in my head and it's between 1-10.
I think this is an issue with how Scanner.nextInt() works. nextInt() takes in the next Integer found but it does not clear the buffer like nextLine() does.
See this link for more info about this issue: How does input.nextInt() work exactly?
Try this and see if your loop continues properly:
while(guessResult != -1) {
randomGuess = GameTwo.nextInt();
guessResult = checkGuess(randomGuess);
GameTwo.nextLine();
System.out.println("Random Guess: " + randomGuess); //Try here
}
I think the reason the loop is getting hung up is because nextInt() keeps finding the randomGuess number still in the input buffer and executing over and over again. To test that, simply put System.out.println("Random Guess: " + randomGuess); in the loop and see if it is printing with the same number over and over again.
Otherwise, I would need to see the output of your program to further diagnose the issue.
Edit: Can you post the input/output of your program up to the point it crashes? This will help. Also, did you have the System.out.println() in your loop beginning with while(guessResult != -1) or the second one?
Edit 2: I tested this code with my edits and it seems to work as intended (ish). The initial while loop does not do what is intended. The "game" aspect of guessing the correct number all happens in the first loop. I am "playing" the game and guess numbers but once I get it correct, it moves to the second loop, presumably where you actually wanted to "play". The correct number is gotten in the first loop and then the guessResult variable gets set to -1. Then when the user tries to guess where they are supposed to, the "correct" number is now -1.
I don't think the game was ever "hung up", it was just silently waiting for your input in the first loop. To solve this:
Simply remove the first while loop (and its contents) and the game works as intended.
So, what I am trying to do is get my while loops to do different things based on different key words. What I want is that when I type yes, I want it to exit the program, when I type no, for it to print a new song, and if there is a spelling error, for a message to pop up and allow the user to re enter yes or no to print the same song. I have 4 or 5 songs that I want to print out based on these three commands. In my last while loop. I want it to repeat the song every time the user types continue, and for it to end when the user types yes. I want the same thing to happen where it prompts the user to type again if there is a spelling error. This worked before, and now it does not. When I make a spelling error, it prompts me to enter again but will not print out the song in that loop. It will send me to the last while loop, ignoring all code in between. That last loop will only recognize spelling errors and yes, not continue, even though it did before.
Here is one song loop and my last loop:
import java.io.*;
import java.util.*;
public class FullNurseryRhymes
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String aBCs, neverEnds, frogs, frogs2, monkeys, hdd, hdd2;
NurseryRhymes rhymes = new NurseryRhymes();
{
System.out.println("Is the baby asleep? yes\\no");
frogs=input.next();
int byeFrog = 2;
for(int i = 3; i >= 1; i--)
{
if (frogs.equalsIgnoreCase("no"))
{
System.out.print(i + " " + rhymes.getFrogs());
System.out.println(" " + byeFrog + " " + rhymes.getFrogs2());
byeFrog -= 1;
}
else if (frogs.equalsIgnoreCase("yes"))
{
System.out.println("The baby is asleep");
System.exit(0);
}
while(!frogs.equalsIgnoreCase("no"))
{
System.out.println("Non requested input, please retry.");
System.out.println("\nIs the baby asleep? continue\\yes");
frogs = input.next();
if(frogs.equalsIgnoreCase("no"))
{
System.out.print(i + " " + rhymes.getFrogs());
System.out.println(" " + byeFrog + " " + rhymes.getFrogs2());
byeFrog -= 1;
}
else if (frogs.equalsIgnoreCase("yes"))
{
System.out.println("The baby is asleep");
System.exit(0);
}
}
}
}
//last loop
{
System.out.println("Is the baby asleep? continue\\yes");
neverEnds = input.next();
while(neverEnds.equalsIgnoreCase("continue"))
{
System.out.println(rhymes.getNeverEnds());
System.out.println("Is the baby asleep? continue\\yes");
neverEnds = input.next();
}
if(neverEnds.equalsIgnoreCase("yes"))
{
System.out.println("The baby is asleep");
System.exit(0);
}
while(!neverEnds.equalsIgnoreCase("continue")||!neverEnds.equalsIgnoreCase("yes"))
{
System.out.println("Non requested input, please retry");
System.out.println("\nIs the baby asleep? continue\\yes");
neverEnds = input.next();
while (neverEnds.equalsIgnoreCase("continue"))
{
System.out.println(rhymes.getNeverEnds());
System.out.println("Is the baby asleep? continue\\yes");
neverEnds = input.next();
if(neverEnds.equalsIgnoreCase("yes"))
{
System.out.println("The baby is asleep");
System.exit(0);
}
}
if (neverEnds.equalsIgnoreCase("yes"))
{
System.out.println("The baby is asleep");
System.exit(0);
}
}
}
Based on the comments, it sounds like there is too much (potentially) relevant code for us to plough through.
There are three ways you could proceed with this.
You could learn how to use the debugger in your IDE. Use breakpoints and single stepping, and figure out where your mistakes are.
You could comment out parts of the code to track down where the problems are. That may also help you to create an MCVE
You could simplify the code by refactoring common / repetitious code into methods. For instance the "last loop" section is incredibly repetitious.
On the last point, it might actually be less work to throw this code away and start again ... after figuring out what common code can be implemented as methods.
Your question is a bit long. We don't need a story, just an explanation of your problem and a BIT of code, not your whole class. Try putting your while loop on the outside. Have a string outside the while loop called babySleep that starts as "no". Then, while(babySleep.equals("no") execute your code. Then at the end, check if the baby is a sleep, if he is, move on, if not, the while loop will re-execute. Also, instead of .equals try .equalsIgnoreCase so the user can type in "Yes" or "yES" etc.
I'm doing the Java Associate level certification and while we are expressly told we won't be tested on labels, we have been shown them. Looking on here though the advice seems to be never use labels?
I'd like to use them in a catch block/user input console as a means of validating input.
do {//Keep calculator going as long as user wants
numInputCheck:
do {
try {//Force user to input a whole number
System.out.print("\nPlease enter the Mark you want to Calculate\n(Enter marks between " + GradeCalculator.getMIN_MARK() + " and " + GradeCalculator.getMAX_MARK() + " only): ");
mark = Integer.parseInt(scn.nextLine());
}catch(NumberFormatException nfe) {
System.out.println("\nInvalid entry - Please ensure entry is a number only.");
continue numInputCheck;
}
gradeCalc.isValidMark(mark);//Ensure input is within valid range
}while(!gradeCalc.getIsValidMark());
*etc*......
Is this bad coding?
EDIT: The code above wasn't doing what I thought it was/wanted it to do - it wasn't actually jumping back to the label at all.
I ended up changing the code to
do {//Keep calculator going as long as user wants
do {//Force user to enter number within valid range
do {//Force user to enter a whole number
try {
System.out.print("\nPlease enter the Mark you want to Calculate\n(Enter marks between " + GradeCalculator.getMIN_MARK() + " and " + GradeCalculator.getMAX_MARK() + " only): ");
mark = Integer.parseInt(scn.nextLine());
isValidInput = true;
}catch(NumberFormatException nfe) {
System.out.println("\nInvalid entry - Please ensure entry is a number only.");
isValidInput = false;
}
}while(!isValidInput);
}while(!gradeCalc.isValidMark(mark));
which I'm fairly sure is working correctly.
Anyway, I think I answered my own question - labels are discouraged because people like me try to use them.
No this is not actual example because continue can do all the job by itself without the help of the label .
A good example is when you have 2 nested loops and you want to break the outer loop from a condition in the inner loop
outerloop:while(condition1) {
while(condition2) {
if(condition3)
break outerloop;
}
{
Continue statement skips all sentences above, you have to use break sentence for stopping the loop. Labels are useful for more than one loop, for example:
label1:
for (int i = 0 ; i<10; i++){
for (int j = 0 ; j<10; j++){
if (i+j = 3)
break label1;
}
}
Ok, so my computer teacher has asked us to make a simple game that asks the user to guess a radomly generated number, but I want to take it one step further and make it so that it display error messages when the user tries certain things. The problem here is that I am new to booleans and well, I am having a bit of trouble using java.util.Scanner and booleans. So, if anyone could take a quick look at this I would appreciate it.
import java.util.Scanner;
import java.util.Random;
public class MoreGuessing{
//Instantiation
Scanner reader = new Scanner(System.in);
Random number = new Random();
//Variables
int randomnumber = number.nextInt(10) + 1;
int cntr = 1;
static String decimalguessed;
String error1 = "Error001: Decimal found, please enter a whole number between 1-10." + "\n" + "Program terminated......";//Decimal portion error.
String error2 = "Please enter a positive number." + "\n" + "Program terminated......"; //Negative number error.
String error3 = "Unknown character entered." + "\n" + "Program terminated......"; //Unknown character error.
//Verifier
public static boolean verifyLetters() {
if (decimalguessed.matches("[a-zA-Z]+")){
return true;
}else{
return false;
}
}
public static void main(String [] args){
//Input and display
System.out.print("Please enter a whole number between 1-10: ");
decimalguessed = reader.nextLine();
//Process and Errors
while (decimalguessed != randomnumber) {
if (verifyLetters() != false){
System.out.println(error3);
System.exit(1);}
if (decimalguessed % 1 != 0) {
System.out.println(error1);
System.exit(1);}
if (decimalguessed < 0) {
System.out.println(error2);
System.exit(1);}
if (randomnumber != decimalguessed){
System.out.println("You've lost, please make another attempt.");}
System.out.print("Please enter a whole number between 1-10: ");
decimalguessed = reader.nextDouble();
cntr++;
}
if (cntr == 1) {System.out.println("Congratulations! You've guessed the number on your first attempt!");;
}
else {System.out.println("Congratulations! You've guessed the number, it took you " + cntr + " tries");}
}
}
You need to parse your input. decimalguessed is a string, and so you can't do comparisons like decimalguessed % 1.
You can convert it to an integer like this:
int guess = 0;
try {
guess = Integer.parseInt(decimalguessed);
} catch (NumberFormatException e) {
System.out.println("Your guess was not an integer: " + e.getMessage());
System.exit(1);
}
This will handle both cases where decimalguessed contains letters, and where it contains decimal points/fractions. decimalguessed is still a string, but guess now contains the integer version of it, so you can compare it to randomnumber properly. (Your loop would have never exited before, because a string is never == an integer)
Some other notes:
You should never have:
if (condition) {
return true;
} else {
return false;
}
This can always be simply replaced with
return condition;
It feels like you're very new to this. Welcome to programming!
So first, in Java generally you're not going to have all of that instantiation and variables stuff outside of your main function, unless you're going to make everything static. I would move all of that into your main function, un-static the decimalguessed variable and setup your verifyLetters function to take an argument of String decimalguessed. It may also be wise to check if the value is a number, rather than seeing if it is not a letter. There a lot of non-number, non-letter characters.
Once you've figured out that the guess is a number, you need to tell java it is one (cast it) to a decimal, then do you further comparisons against that decimal.
Darth Android also makes some good points, especially about booleans. You should never have the only result of an if/else be to return a boolean, just return the boolean. Also avoid comparisons to true/false, just do the if on the function/variable alone, or negate it with an '!' to check for false.
Good luck!
I am trying to make a quiz for an assignment in my GCSE computing course, and I need some help. This code compiles but whenever I run the code and input an answer, the answer spills over onto the answer for another question. For example, for the first question if I type the answer as "Mr Someone" when I am running the program, "Mr" becomes the answer to the first question and "Someone" becomes the answer to the second.
I'm not sure if this has anything to do with the sub-strings or what, but please help! :). If you're wondering why the value for the iScore variable is never used, it's because this is not the full code, just the first three questions, the score is printed at the end. There is not difference in the "template" for each question, just a different question and answer.
public static void main(String[] args) throws InterruptedException
{
//creates the Scanners needed
Scanner szAnswer = new Scanner(System.in);
Scanner szPlayAgain = new Scanner(System.in);
//declares the variables for the answers
String szFirstAnswer;
String szSecondAnswer;
String szThirdAnswer;
//declares a variable for the score
int iScore = 0;
//declares a variable for whether or not the user wants to keep playing
String szRestart;
//creates a do while loop, keeps going as long as the user wants to play
do {
//tells the user that only one word answers are needed
System.out.println("Only one word answers are needed!");
//first question
//Asks the question and collects the input
System.out.println("Question 1:");
System.out.print("Which Ancient Greek god was said to be the god of the sky? ");
szFirstAnswer = szAnswer.next();
//converts the answer to a format with the first letter upper case and the rest lower case
szFirstAnswer = szFirstAnswer.substring(0,1).toUpperCase() + szFirstAnswer.substring(1);
szFirstAnswer = szFirstAnswer.substring(0,1) + szFirstAnswer.substring(1).toLowerCase();
//prints out the converted response
System.out.println("You said: " + szFirstAnswer);
//if the answer was Zeus, the print out correct and add 1 to the score
if (szFirstAnswer.equals("Zeus")) {
System.out.println("Correct!");
iScore++;
}
//if the answer was not Zeus, print out a message with the correct answer
else {
System.out.println("Wrong! The correct answer was: Zeus");
}
//creates a line break
System.out.println();
//second question
//Asks the question and collects the input
System.out.println("Question 2:");
System.out.print("Which team has won the most FA Cups since the competition started? ");
szSecondAnswer = szAnswer.next();
//converts the answer to a format with the first letter upper case and the rest lower case
szSecondAnswer = szSecondAnswer.substring(0,1).toUpperCase() + szSecondAnswer.substring(1);
szSecondAnswer = szSecondAnswer.substring(0,1) + szSecondAnswer.substring(1).toLowerCase();
//prints out the converted response
System.out.println("You said: " + szSecondAnswer);
//if the answer was Arsenal, the print out correct and add 1 to the score
if (szSecondAnswer.equals("Arsenal")) {
System.out.println("Correct!");
iScore++;
}//end if
//if the answer was not Arsenal, print out a message with the correct answer
else {
System.out.println("Wrong! The correct answer was: Arsenal");
}//end else
//creates a line break
System.out.println();
//third question
//Asks the question and collects the input
System.out.println("Question 3:");
System.out.print("What is the currency of Japan? ");
szThirdAnswer = szAnswer.next();
//converts the answer to a format with the first letter upper case and the rest lower case
szThirdAnswer = szThirdAnswer.substring(0,1).toUpperCase() + szThirdAnswer.substring(1);
szThirdAnswer = szThirdAnswer.substring(0,1) + szThirdAnswer.substring(1).toLowerCase();
//prints out the converted response
System.out.println("You said: " + szThirdAnswer);
//if the answer was Yen, the print out correct and add 1 to the score
if (szThirdAnswer.equals("Yen")) {
System.out.println("Correct!");
iScore++;
}//end if
//if the answer was not Yen, print out a message with the correct answer
else {
System.out.println("Wrong! The correct answer was: Yen");
}//end else
//creates a line break
System.out.println();
}while (szRestart.equals("Y"));//end while
//prints a thank you message to the screen
System.out.println("Thanks for Playing!");
//closes the scanners
szAnswer.close();
szPlayAgain.close();
}//end main
Where you have szAnswer.next(); you should actually have szAnswer.nextLine(); I believe.
.next() gets the next word that is input, which is why it stops at the first space, where as .nextLine(); gets the whole line when you hit enter.