Boolean method with an incorrect input - java

I'm a bit stuck on an exercice I have to make and I can't figure out the best way to do it.
I have to make a method that asks a question and expects Y or N. So I thought I would make a boolean method to return true or false, but the problem is that it would also return false if the user puts something other than Y or N. If I'm not mistaken, a boolean method cannot return null.
I'm very new to java and I'm not very far in my course so this problem will probably have a very simple solution. I also tried looking for an answer but didn't seem to find what I was looking for.
This is what I have with the boolean method but i'm not quite happy with it:
public static boolean test() {
Scanner sc = new Scanner(System.in);
System.out.println("question");
String reponse = sc.next();
if (reponse.equalsIgnoreCase("Y")) {
return true;
}
else if (reponse.equalsIgnoreCase("N")) {
return false;
}
else {
return false;
}
}

You need only one condition equalsIgnoreCase("Y"), result of its evaluation is basically the return value. All the if-statements in your code are redundant.
public static boolean test() {
Scanner sc = new Scanner(System.in);
System.out.println("question");
String reponse = sc.next();
return reponse.equalsIgnoreCase("Y"));
}

Going by your comment you want your program to ask for input again if the input is neither "y" nor "n". You can achieve that behavior by adding an extra loop:
public static boolean test() {
Scanner sc = new Scanner(System.in);
System.out.println("question");
String response = sc.next();
while(!response.equalsIgnoreCase("Y") && !response.equalsIgnoreCase("N")) {
// loop as long as input is neither "y" nor "n" (ignoring case)
System.out.println("Please enter 'y' or 'n'");
reponse = sc.next();
}
// if the loop is done input has to be either "y" or "n" at this point
return reponse.equalsIgnoreCase("y");
}

The problem is at the end you are explicitly telling java to return false when neither a Y or N is entered. I would try putting in another else statement to have the user re-enter the data or just notify them that they have entered the wrong value.
public static boolean test() {
Scanner sc = new Scanner(System.in);
System.out.println("question");
String reponse = sc.next();
while(!response.equalsIgnoreCase("Y") ||!response.equalsIgnoreCase("N"){
#Do something here until
the user inputs the correct value.
}
}

Related

Scanner doesn't update input when returning to method Java

I'm writing a word-guessing game code. The main calls the inputTake method, which asks for input of a word consisting 5 English letters only, and returns is. Before returning the word, it calls another method, checkInput, to make sure the input is valid. If the input isn't valid, the checkInput method prints an error message and calls inputTake to let the user try again.
But when the first input is invalid, checkInput calls inputTake and then the second input is valid everything seems to work alright. The problem is that the method returns the first, invalid input, and not the valid input.
I tried initializing Scanner in the main and giving it to the method as parameter, but that doesn't help.
Below is the code I wrote, any thoughts? Any help is welcome
Main:
Board board1 = new Board();
String guess = board1.inputTake();
Board:
// take input - print a message and calls the checkInput method with the String inputed.
public String inputTake(){
Scanner scan = new Scanner(System.in);
String guess;
System.out.println("choose a word, pick carefully: ");
guess = scan.next();
// we gotta check whether the input's valid before we return it!
checkInput(guess);
return guess;
}
/* checks whether a given String is made out of 5 english language letters.
* if it is, program continues normally.
* if not, it prints error message and calls the InputTake method again.
*/
public void checkInput(String input) {
boolean isGood = true;
// check if 5 letters
if(input.length() != 5)
isGood = false;
// check if all are english
if(!input.matches("[a-zA-Z]+"))
isGood = false;
if(isGood == false) {
System.out.println("make sure your guess consists of 5 english letters, try again.");
inputTake();
}
}
As mentioned in the comments, the problem is that your inputTake() call inside checkInput() doesn't do what you want. You can try this:
// take input - print a message and calls the checkInput method with the String inputed.
public String inputTake(){
Scanner scan = new Scanner(System.in);
String guess;
System.out.println("choose a word, pick carefully: ");
guess = scan.next();
// we gotta check whether the input's valid before we return it!
if(!isGoodInput(guess)) {
System.out.println("make sure your guess consists of 5 english letters, try again.");
guess = inputTake();
}
return guess;
}
/* checks whether a given String is made out of 5 english language letters.
* if it is, program continues normally.
*/
public boolean isGoodInput(String input) {
return input.length() == 5 && input.matches("[a-zA-Z]+");
}

How do I use boolean method correctly if I need two options?

The question is, if I need to chose only from two options in boolean method (Yes or No) how do I put it in IFs?
I try to do like this (see below), it underlines very last brace. If I use default return outside while (but I don't want to), it underlines first return (after first if).
static boolean isAnotherGamer() {
System.out.println("Play another game? Type in Y or N");
Scanner scanner = new Scanner(System.in);
String answer = scanner.nextLine();
while (true) {
if (answer.equalsIgnoreCase("Y")) {
break;
return true;
} else if (answer.equalsIgnoreCase("N")) {
break;
return false;
}
System.out.println("Input mismatch");
} //IDE underline this brace
}
Here is how I would do it. This allows any part of yes or no to be entered. I think it best to pass a Scanner instance rather than creating one each time. Using a regular expression allows for some latitude in the answer.
^$ - beginning and end of string.
(?i) - ignore case
ye?s? - says must have y but e and s are optional.
static boolean isAnotherGamer(Scanner scanner) {
System.out.println("Play another game? Type in Y(es) or N(o)");
while (true) {
String input = scanner.nextLine();
if (input.matches("(?i)^ye?s?$")) {
return true;
}
if (input.matches("(?i)^no?$")) {
return false;
}
System.out.println("Incorrect response, please enter Y(es) or N(o)");
}
}
Why can you not validate the input first, and then after the input is either a yes or no, decide on what to do. If it is not either, you can make the repetition statement continue to run until after you get what you need. The location of your return statement is the problem because if either if or else if statements are not true, the method will not return a boolean as your method signature suggests, and your method will just be an infinite loop.
Your method is declared to return a boolean. There is no return statement in the flow.
Assume you go into the endless loop. At this moment we evaluate what the user entered (why do we do that inside the endless loop? The answer does not change inbetween, does it?)
If it is 'y', we break the loop.
If it is 'n', we break the loop.
In any other case we print something and remain in the loop.
But as soon as the loop was broken -> where is the return statement?
So from my POV, the function should look like this:
static boolean isAnotherGamer() {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Play another game? Type in Y or N");
String answer = scanner.nextLine();
if (answer.equalsIgnoreCase("Y")) {
return true;
} else if (answer.equalsIgnoreCase("N")) {
return false;
}
System.out.println("Input mismatch");
}
}
Because you've not set a default return value, if the user doesn't choose either "Y" or "N" then nothing is going to be returned so that's why you're getting an error.
Additionally, you shouldn't be putting any code after your break statements as those lines will be completely ignored (again, nothing returned as your return statements are after your breaks.)
You can just completely remove those break statements if you're just wanting to quit that method once you've got your boolean value or you can update a boolean variable for future use if you're wanting to keep running code inside your method. (I've provided an example of this)
System.out.println("Play another game? Type in Y or N");
Scanner scanner = new Scanner(System.in);
String answer = scanner.nextLine();
//To store the state of the user's answer
boolean providedAnswer = false;
//if the answer was yes, set the boolean's val to true
if(answer.equalsIgnoreCase("Yes")){
providedAnswer = true;
}
//output the boolean's value
System.out.println("User wanted to play again? " + providedAnswer);
//return the boolean value
return providedAnswer;
}```

can the program be terminated early from within a methood

I am making a simple "game" where the user is asked a question and must give the correct answer to move on this is the code I currently have for one of the questions.
public static void Mascot() {
Scanner console = new Scanner(System.in);
System.out.println("what Is our school mascot?");
String Tony = console.nextLine();
String b = Tony;
Scanner scanner= new Scanner(b);
if (scanner.hasNext("tiger")){
System.out.println("Good, next riddle.");
} else{
}
scanner.close();
console.close();
}
I want the if statement to be case-insensitive and return true if tiger is input in the scanner at all. like someone could enter a full sentence into the scanner and if the word tiger is anywhere it returns as true. but if tiger (or any other incorrect answer for any other question is input in the scanner, I want the program to stop. and not continue to the next question.
Couple of things to note here.
Whether to continue the game or not should ideally be controlled by the caller of the method. The caller of the method should decide based on the return value true or false
To accommodate (1) method signature needs to change. It can't be void. It should be boolean.
You don't need the second scanner object to verify if it contains tiger
Please check if this code helps you
public static boolean Mascot() {
Scanner console = new Scanner(System.in);
try {
System.out.println("what Is our school mascot?");
String b = console.nextLine();
if (b.toLowerCase().contains("tiger")){
System.out.println("Good, next riddle.");
return true;
} else{
return false;
}
}
catch(Exception e) {
System.out.println("Exception Occurred");
}
finally {
console.close();
}
return false;
}

How can I make a java program to understand the user-input "t" as "true" and "f" as "false"(boolean)?

I have to code a program, that's working with boolean operators. The first thing this program should do is to ask the user for an operator by "command:". The user can only enter "&&", "||", "!" and "quit". Quit just shuts down the program. The next thing it does is to ask the user for a boolean variable, but here is my problem: The program works perfectly fine with entering "true" or "false", but the task I've got says, the user can only use "t" for "f" as input. So here is my question: How can I make the program to understand "t" as "true" and "f" as "false"?(by the way if the user enters"!" the program just outputs the negation of the first parameter)
public static void main(String[] args) {
Scanner eingabe = new Scanner(System.in);
System.out.println("Command: ");
String command = eingabe.nextLine();
if(command.equals("quit")) {
System.exit(0);
}
System.out.println("Parameter 1:");
boolean parameter1=eingabe.nextBoolean();
if(command.equals("!")) {
System.out.println(!parameter1);
System.exit(0);
}
System.out.println("Parameter 2:");
boolean parameter2=eingabe.nextBoolean();
if(command.equals("&&")) {
System.out.println(parameter1&&parameter2);
}else if(command.equals("||")) {
System.out.println(parameter1||parameter2);
}
eingabe.close();
}
}
The easiest way would be to write a little method, something like:
boolean customParseBoolean(String input) {
if ("t".equals(input)) {
return true;
} else if ("f".equals(input)) {
return false;
}
// You don't have to throw an exception on invalid input; just an example.
throw new IllegalArgumentException("Invalid input: " + input);
}
and then invoke this something like:
boolean parameter1 = customParseBoolean(eingabe.nextLin());
It doesn't matter which way you do it, but below should work for your example. It just doesn't cover the case when the input is malformed
String parameterString1 = eingabe.next();
boolean parameter1 = !command.equals("f");
String parameterString2 = eingabe.next();
boolean parameter2 = command.equals("t");
you can always cross verify the user input in if() condition. create a boolean value with false by default, if the user types t make that boolean as true and vice versa.
or else u can use switch statements

Make Java Program Loop until x is entered?

I want to make my program loop until the user types in x instead of a number. I tried using a while statement but I do not know how to use it with multiple variables. Here is my code
public static void main(String[] args)
{
int denominatorOne = 1, numeratorOne = 1;
System.out.println("Welcome, type an \"x\" at any point to exit the program");
while (numeratorOne !=x)
{
Scanner in = new Scanner(System.in);
//Prompt the user for fraction one
System.out.print("Enter the first numerator (top number): ");
numeratorOne = in.nextInt();
System.out.print("Enter the first denominator (bottom number): ");
denominatorOne = in.nextInt();
}
}
The exact phrasing from my assignment is The program should run in loop and allow the user to exit with some special character input (e.g. x or X to exit)
First off, 'x' isn't a number and won't be accepted by nextInt or a comparison to 'x', you should trying checking to see if it has next int (in.hasNextInt()) and process depending. Besides the point, you can easily test two variables in a while loop. Assuming you set up the variables right to be chars:
do {
// scan code.
} while(!(numChar1.equals('x') && numChar2.equals('x')))
what you need to do is have a bool value that holds the loop and when have a if statement check for the keydown event in the loop
bool looping = true
while ( looping == true)
{
if (x button was pressed == true)
{looping = false
}
}
try changing it to
while(!numeratorOne.equals("x")){...}
You can just call the method over again in this case main();.
What I suggest however is to create a new method, in the method just checking the users input returning the input as a string. Then you can check the string in your main method, and if that's not the string you wanted then recall the method. Here's an example, please note I didn't use an IDE for this.
public String getMessage(){
Scanner input = System.in();
return input;
}
public void checkMessage(String wantedString){
if(!getMessage().equalsIgnoreCase(wantedString)){
System.out.println("Please retry");
checkMessage();
}
}
public static void main(String[] args){
checkMessage();
}

Categories