1

Hello i'm currently a beginner in Java. The code below is a while loop that will keep executing until the user inputs something other than "yes". Is there a way to make the scanner accept more than one answer? E.g. yes,y,sure,test1,test2 etc.

import java.util.Scanner;

public class Test {        

    public static void main(String[] args) { 

        Scanner in = new Scanner(System.in);
        String ans = "yes";
        while (ans.equals("yes")) 
        {
            System.out.print("Test ");
            ans = in.nextLine();
        }        
    }
}
1
  • You are looking for a method to check whether a given string is included in a List of string values like ["yes", "sure", "..."]. Some Answers here will help you solve your problem. Commented Mar 11, 2017 at 8:16

3 Answers 3

1

Use the or operator in your expression

while (ans.equals("yes") || ans.equals("sure") || ans.equals("test1"))  
        {
            System.out.print("Test ");
            ans = in.nextLine();
        } 

But if you are going to include many more options, it's better to provide a method that takes the input as argument, evaluates and returns True if the input is accepted.

Sign up to request clarification or add additional context in comments.

Comments

0

Don't compare the user input against a value as loop condition?!

Respectively: change that loop condition to something like

while(! ans.trim().isEmpty()) {

In other words: keep looping while the user enters anything (so the loop stops when the user just hits enter).

Comments

0

You are looking for a method to check whether a given string is included in a List of string values. There are different ways to achieve this, one would be the use of the ArrayList contains() method to check whether your userinput in appears in a List of i.e. 'positive' answers you've defined.

Using ArrayList, your code could look like this:

import java.util.Scanner;

public class Test { 

    public static void main(String[] args) { 

        ArrayList<String> positiveAnswers = new ArrayList<String>();
        positiveAnswers.add("yes");
        positiveAnswers.add("sure");
        positiveAnswers.add("y");     

        Scanner in = new Scanner(System.in);
        String ans = "yes";

        while (positiveAnswers.contains(ans)) 
        {
            System.out.print("Test ");
            ans = in.nextLine();
        }        
    }
}

1 Comment

Why not use some kind of Set for this, instead of an ArrayList? It would be way more efficient if there are lots of terms to check; and the code would be no more complex (in fact, almost identical).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.