Java:如何获取Scanner对象以忽略不需要的/无效的输入? [英] Java: How do I get a Scanner object to ignore unwanted/invalid inputs?

查看:67
本文介绍了Java:如何获取Scanner对象以忽略不需要的/无效的输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试建立一个简单的文本树,该树可以读取单个字符(y/n)或与打印列表相对应的整数(1-4).我想知道让程序忽略不符合给定选项的用户输入的最简单方法:

I am trying to set up a simple text tree that reads in either single-characters (y/n) or integers that correspond to a printed list (1-4). I want to know the easiest way to have the program ignore user inputs that don't correspond to the given options like so:

import java.util.Scanner;

public class simpleMenu
{
    Scanner sc = new Scanner(System.in);
    String choicePick;

    public static void main(String[] args)
    {
        System.out.println("Would you like to continue? (y/n)");
        choicePick = sc.next();

        if(choicePick.equals("y"))
        {
            // The program continues.
        } 
        else if(choicePick.equals("n"))
        { 
            // The program closes.
        } 
        else 
        {
            /* 
            The scanner ignores the input, ideally without having to restate the question.
            The program does not quit or move on until "y" or "n" is entered.
            */ 
        }
    }
}

如果您可以帮助我实施后退"选项,使我进入先前的选择,则奖励积分.

Bonus points if you can help me implement a 'back' option that takes me to the previous choice.

推荐答案

下一个字符串不是Y或N sc.next(),直到它是.然后使用该字符串.

While the next string is not Y or N sc.next() until it is. Then use that string.

这篇关于Java:如何获取Scanner对象以忽略不需要的/无效的输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆