John Johnston
John Johnston

Reputation: 11

How to make java scanner accept more than one string input?

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

Upvotes: 1

Views: 603

Answers (3)

The F
The F

Reputation: 3714

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

Upvotes: 0

Gerry Hernandez
Gerry Hernandez

Reputation: 352

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.

Upvotes: 1

GhostCat
GhostCat

Reputation: 140427

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

Upvotes: 0

Related Questions