can the program be terminated early from within a methood - java

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

Related

Boolean method with an incorrect input

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

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

java.util.NoSuchElementException: No line found exception when using scanner inside the loop

I have a requirement of taking input inside a loop but getting an issue saying such as NoSuchElementException. Not really sure about the issue.
To give some information about my requirement, I have to perform a function if the user types yes continuously until the user type no.
Code:
// Toppings
while(true) {
Scanner st = new Scanner(System.in);
System.out.println("Do you need to add more toppings: (yes/no)");
String decision = st.nextLine();
if (decision.equals("yes")) {
cake = toppingOption(cake);
} else if (decision.equals("no")) {
st.close();
break;
} else {
System.out.println("Wrong input, type (yes/no)");
}
}
You have more than one Scanner that you close, which closes the underlying InputStream, therefore another Scanner can no longer read from the same InputStream and a NoSuchElementException results.
Move st out of while loop
Scanner st = new Scanner(System.in);
// Toppings
while(true) {
System.out.println("Do you need to add more toppings:(yes/no)");
String decision = st.nextLine();
if(decision.equals("yes")) {
cake = toppingOption(cake);
}
else if(decision.equals("no")) {
st.close();
break;
}
else {
System.out.println("Wrong input, type (yes/no)");
}
}
My question is incomplete, inside the toppingOptions function I have another scanner object which I close, so after I remove the scanner objects close this work.

Scanner Class ~ hasNextDouble();

package pkgswitch;
import java.util.Scanner;
public class Switch {
public static void main(String[] args) {
double subtotal = 0.0;
Scanner sc = new Scanner(System.in);
outerloop:
while(0==0){
System.out.print("Enter subtotal: ");
if (sc.hasNextDouble())
{
subtotal=sc.nextDouble();
}
else
{
sc.nextLine();
System.out.println("Error!");
continue outerloop;
}
}
}
}
I'm working with learning how to catch exceptions. (I know about the try / catch)
Question:
How does scanner have more double tokens when it has just been initialized with no input
How does scanner have more double tokens when it has just been initialized with no input?
Your code doesn't initialize the scanner with "no input". It initializes it with System.in.
What actually happens is that sc.hasNextDouble() attempts to read and buffer characters from the input stream ... blocking if the user hasn't typed them yet. When the method has enough characters to determine if it has a valid double token, it returns true ... or false.
By the way:
while (0 == 0) {
is silly. Please don't do it. It causes the reader to waste his / her time:
figuring out what the code is really doing, and
wondering whether the author doesn't understand basic Java, or has been using illegal substances while coding ... :-)
System.in is an InputStream. From javadoc, read "blocks until input data is available, the end of the stream is detected, or an exception is thrown".
It doesn't. Check this out: I've added two print statements to your code. If you run this, you'll see that the method hasNextDouble() does not return anything until after you've entered a value. So if you type a double, then hasNextDouble() will return true, and the program will set the subtotal to that value (also, not sure, but it seems to me you may want to add to subtotal instead of setting it's value).
public static void main(String[] args) {
double subtotal = 0.0;
Scanner sc = new Scanner(System.in);
outerloop:
while(0==0){
System.out.print("Enter subtotal: ");
if (sc.hasNextDouble())
{
System.out.println("has next double."); /* added */
subtotal=sc.nextDouble();
System.out.println("read double: "+subtotal);
}
else
{
System.out.println("no next double"); /* added */
sc.nextLine();
System.out.println("Error!");
continue outerloop;
}
}
}
first of all it is nice to have while(true) than while(0==0) .When It prints "Enter Sub total" you can give a double (ex 3.0).Then sc.hasNextDouble() becomes true and whatever the code in if statement runs.If you give a input which is not double(ex 'k') then sc.hasNextDouble() becomes false and whatever in the else is running.

Scanner looping headache

I have a homework assignment which requires input from the user and stores it in various data structures (arrays of linked-lists, stacks, etc.). However, I've been writing the main class of my previous homework assignments and this one in a very similar fashion. I have a very tiny main method. All the main method does is instantiate a new object which I don't want to be destroyed and then loop through the program forever until the user chooses otherwise. I then have a menu() method which prints a list of selections and reads the user's selection. And then from there, I pass that selection to another method which interprets the selection and performs accordingly.
The problem I have been having in the past assignments and now I've never really gotten a good answer for. The problem seems to lie with my menu() method and more specifically, the Scanner object. There always seems to be some junk left in the stream after I call the nextLine() method on a scanner object. So the next time the menu() method is called, it reads in that junk and loops though the rest of the program with that junk until menu() is called a third time. In the past, I would remedy this by calling the next() method right after I received my input and ignoring it. However, I seem to be having issues with that now as well.
In this program in particular, I have a method which request's a user enter a city name. Now, city names can be more than one word (Palm City, West Palm Beach, Satellite Beach, New York, etc.). Now, when the scanner reads in one of those multi-word cities, it does the same thing as before, reads in some junk the next time the menu() method is called and goes though the whole program with it until menu() is called again. In this case, it prints an string "Invalid Selection" and then prints the menu again. I can't for the life of me figure out what's going on. any help would be appreciated.
import java.util.Scanner;
public class CSAir
{
public static Scanner input = new Scanner(System.in);
public static void main(String[] args)
{
CityList flightLog = new CityList();
boolean loop = true;
while(loop)
{
loop = actions(menu(),flightLog);
}
}
private static String menu()
{
System.out.print("Please Make a Selection\n" +
"I) Insert a city\n" +
"A)Add a flight path (One Way)\n" +
"R) Request a flight\n" +
"L) Load from a text file\n" +
"Q) Quit\n" +
"\nSelection: ");
String in = input.next();
//input.next();
System.out.println();
return in;
}
private static boolean actions(String selection, CityList flightLog)
{
if(selection.equalsIgnoreCase("I"))
{
insert(flightLog);
return true;
}
else if(selection.equalsIgnoreCase("A"))
{
add(flightLog);
return true;
}
else if(selection.equalsIgnoreCase("R"))
{
request(flightLog);
return true;
}
else if(selection.equalsIgnoreCase("L"))
{
return true;
}
else if(selection.equalsIgnoreCase("Q")) return false;
else
{
System.out.println("Invalid Selection!\n");
return true;
}
}
private static void request(CityList flightLog)
{
System.out.print("Origin: ");
String origin = input.nextLine();
System.out.print("\nDestination: ");
try
{
flightLog.isPath(origin, input.next());
}
catch (AllDestinationsVisitedException e)
{
e.getMessage();
}
}
private static void add(CityList flightLog)
{
System.out.print("Origin: ");
String origin = input.nextLine();
System.out.print("\nDestination: ");
flightLog.addPath(origin, input.next());
}
private static void insert(CityList flightLog)
{
System.out.print("Enter a City: ");
try
{
flightLog.addCity(input.next());
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
System.out.println();
}
}
Default Deliminator for scanner is white space. So when you enter New York since it has white space now scanner treats it as two tokens if you call next().
A better option would be to use nextLine() method for reading such values.

Categories