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();
        }        
    }
}
The F
  • 3,647
  • 1
  • 20
  • 28
  • 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](http://stackoverflow.com/questions/1128723/how-can-i-test-if-an-array-contains-a-certain-value) will help you solve your problem. – The F Mar 11 '17 at 08:16

3 Answers3

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.

Gerry Hernandez
  • 342
  • 1
  • 2
  • 13
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).

GhostCat
  • 137,827
  • 25
  • 176
  • 248
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();
        }        
    }
}
The F
  • 3,647
  • 1
  • 20
  • 28
  • 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). – Dawood ibn Kareem Mar 11 '17 at 11:21