java - 如何使用java.util.Scanner从System.in正确读取用户输入并对其进行操作?

标签 java java.util.scanner system.in

This is meant to be a canonical question/answer that can be used as a duplicate target. These requirements are based on the most common questions posted every day and may be added to as needed. They all require the same basic code structure to get to each of the scenarios and they are generally dependent on one another.



扫描程序似乎是要使用的“简单”类,这是犯下第一个错误的地方。这并不简单,它具有各种非显而易见的副作用和异常行为,这些行为以非常微妙的方式破坏了“最小惊讶原则”。

因此,对于这个类(class)来说,这似乎是过高的选择,但是剥皮洋葱的错误和问题都很简单,但由于它们的相互作用和副作用,将它们加在一起非常复杂。这就是为什么每天在Stack Overflow上有这么多问题的原因。

扫描仪常见问题:

大多数Scanner问题都包括尝试失败的原因之一。
  • 我希望能够让我的程序也自动在每个先前输入之后等待下一个输入。
  • 我想知道如何检测退出命令并在输入该命令时结束我的程序。
  • 我想知道如何以不区分大小写的方式将多个命令与exit命令匹配。
  • 我希望能够匹配正则表达式模式以及内置基元。例如,如何匹配日期(2014/10/18)?
  • 我想知道如何匹配用正则表达式匹配可能不容易实现的东西,例如URL(http://google.com)。

  • 动机:

    在Java世界中,Scanner是一个特例,它是一个非常挑剔的类,老师不应该给新学生使用说明。在大多数情况下,讲师甚至都不知道如何正确使用它。它几乎没有在专业的生产代码中使用过,因此其对学生的值(value)极具疑问。

    使用Scanner意味着该问题和答案提到的所有其他内容。这绝不仅仅是关于Scanner的问题,而是关于如何使用Scanner解决这些常见的问题,这些问题在几乎所有会导致Scanner错误的问题中始终是共同的问题。它不仅仅与 next() vs nextLine() 有关,还只是该类实现的复杂性的征兆,在代码发布中总是存在其他问题,这些问题涉及关于Scanner的问题。

    答案显示了99%情况下的完整惯用实现,其中Scanner在StackOverflow上使用并询问过。

    特别是在初学者代码中。如果您认为此答案过于复杂,请向指导新学生的讲师提示,他们在解释其错综复杂,怪癖,非显而易见的副作用以及其行为特点之前,请使用Scanner
    Scanner是一个很棒的教学时机,它说明Principle of least astonishment多么重要以及为什么一致的行为和语义在命名方法和方法参数时很重要。

    给学生的注意事项:

    You will probably never actually see Scanner used in professional/commercial line of business apps because everything it does is done better by something else. Real world software has to be more resilient and maintainable than Scanner allows you to write code. Real world software uses standardized file format parsers and documented file formats, not the adhoc input formats that you are given in stand alone assignments.

    最佳答案

    惯用例:

    以下是如何正确使用java.util.Scanner类从System.in(有时称为stdin,以交互方式)中正确读取用户输入的信息,尤其是在C,C++和其他语言以及Unix和Linux中。它惯用地演示了要求完成的最常见的事情。

    package com.stackoverflow.scanner;
    
    import javax.annotation.Nonnull;
    import java.math.BigInteger;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.util.*;
    import java.util.regex.Pattern;
    
    import static java.lang.String.format;
    
    public class ScannerExample
    {
        private static final Set<String> EXIT_COMMANDS;
        private static final Set<String> HELP_COMMANDS;
        private static final Pattern DATE_PATTERN;
        private static final String HELP_MESSAGE;
    
        static
        {
            final SortedSet<String> ecmds = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
            ecmds.addAll(Arrays.asList("exit", "done", "quit", "end", "fino"));
            EXIT_COMMANDS = Collections.unmodifiableSortedSet(ecmds);
            final SortedSet<String> hcmds = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
            hcmds.addAll(Arrays.asList("help", "helpi", "?"));
            HELP_COMMANDS = Collections.unmodifiableSet(hcmds);
            DATE_PATTERN = Pattern.compile("\\d{4}([-\\/])\\d{2}\\1\\d{2}"); // http://regex101.com/r/xB8dR3/1
            HELP_MESSAGE = format("Please enter some data or enter one of the following commands to exit %s", EXIT_COMMANDS);
        }
    
        /**
         * Using exceptions to control execution flow is always bad.
         * That is why this is encapsulated in a method, this is done this
         * way specifically so as not to introduce any external libraries
         * so that this is a completely self contained example.
         * @param s possible url
         * @return true if s represents a valid url, false otherwise
         */
        private static boolean isValidURL(@Nonnull final String s)
        {
            try { new URL(s); return true; }
            catch (final MalformedURLException e) { return false; }
        }
    
        private static void output(@Nonnull final String format, @Nonnull final Object... args)
        {
            System.out.println(format(format, args));
        }
    
        public static void main(final String[] args)
        {
            final Scanner sis = new Scanner(System.in);
            output(HELP_MESSAGE);
            while (sis.hasNext())
            {
                if (sis.hasNextInt())
                {
                    final int next = sis.nextInt();
                    output("You entered an Integer = %d", next);
                }
                else if (sis.hasNextLong())
                {
                    final long next = sis.nextLong();
                    output("You entered a Long = %d", next);
                }
                else if (sis.hasNextDouble())
                {
                    final double next = sis.nextDouble();
                    output("You entered a Double = %f", next);
                }
                else if (sis.hasNext("\\d+"))
                {
                    final BigInteger next = sis.nextBigInteger();
                    output("You entered a BigInteger = %s", next);
                }
                else if (sis.hasNextBoolean())
                {
                    final boolean next = sis.nextBoolean();
                    output("You entered a Boolean representation = %s", next);
                }
                else if (sis.hasNext(DATE_PATTERN))
                {
                    final String next = sis.next(DATE_PATTERN);
                    output("You entered a Date representation = %s", next);
                }
                else // unclassified
                {
                    final String next = sis.next();
                    if (isValidURL(next))
                    {
                        output("You entered a valid URL = %s", next);
                    }
                    else
                    {
                        if (EXIT_COMMANDS.contains(next))
                        {
                            output("Exit command %s issued, exiting!", next);
                            break;
                        }
                        else if (HELP_COMMANDS.contains(next)) { output(HELP_MESSAGE); }
                        else { output("You entered an unclassified String = %s", next); }
                    }
                }
            }
            /*
               This will close the underlying InputStream, in this case System.in, and free those resources.
               WARNING: You will not be able to read from System.in anymore after you call .close().
               If you wanted to use System.in for something else, then don't close the Scanner.
            */
            sis.close();
            System.exit(0);
        }
    }
    

    笔记:

    This may look like a lot of code, but it illustrates the minimum effort needed to use the Scanner class correctly and not have to deal with subtle bugs and side effects that plague those new to programming and this terribly implemented class called java.util.Scanner. It tries to illustrate what idiomatic Java code should look like and behave like.



    以下是编写此示例时我正在考虑的一些事项:

    JDK版本:

    我特意使该示例与JDK 6兼容。如果某些情况确实需要JDK 7/8的功能,我或其他人将发布新答案,并提供有关如何针对该版本JDK进行修改的详细说明。

    关于这个类的大多数问题来自学生,他们通常对解决问题的方式有限制,因此我尽可能地限制了这一点,以展示如何在没有任何其他依赖的情况下完成常见的事情。在过去22多年的时间里,我一直在使用Java并咨询大部分时间,在我所看到的10百万行的源代码中,从未遇到过此类的专业用途。

    处理命令:

    这准确地显示了idiomatically如何以交互方式从用户读取命令并分发这些命令。有关java.util.Scanner的大多数问题是输入特定输入类别后如何退出程序的问题。这清楚地表明了这一点。

    天真的调度员

    分发逻辑是故意天真的,以免使新读者的解决方案复杂化。基于Strategy PatternChain Of Responsibility模式的调度程序将更适合于现实世界中更为复杂的问题。

    错误处理

    该代码被故意构造为不需要Exception处理,因为在某些情况下某些数据可能不正确。
    .hasNext().hasNextXxx()
    我很少看到有人正确地使用.hasNext(),通过测试通用.hasNext()来控制事件循环,然后使用if(.hasNextXxx())惯用法让您决定如何以及以何种方式继续执行代码,而不必担心在没有int的情况下可用,因此没有异常处理代码。
    .nextXXX().nextLine()
    这会破坏每个人的代码。这是一个finicky detail,不应该处理,并且有一个很难理解的错误,因为它破坏了Principal of Least Astonishment
    .nextXXX()方法不占用行尾。 .nextLine()可以。

    这意味着在.nextLine()之后立即调用.nextXXX()只会返回行尾。您必须再次调用它才能实际获得下一行。

    这就是为什么许多人主张要么只使用.nextXXX()方法,要么只使用.nextLine(),但不要同时使用两种方法,以免这种挑剔的行为不会使您绊倒。我个人认为类型安全方法比必须手动测试和解析并捕获错误要好得多。

    不确定性:

    请注意,代码中没有使用可变变量,这对于学习如何使用非常重要,它消除了运行时错误和细微错误的四个最主要来源。
  • 没有nulls意味着不可能有NullPointerExceptions!
  • 没有可变性,这意味着您不必担心方法参数更改或其他任何更改。在逐步调试时,您无需使用watch即可查看哪些变量更改为什么值(如果它们正在更改)。这使逻辑在您阅读时100%确定。
  • 没有可变性,意味着您的代码是自动线程安全的。
  • 没有副作用。如果什么都不能改变,那么您就不必担心某些边缘情况意外更改某些细微的副作用!

  • Read this if you don't understand how to apply the final keyword in your own code.

    使用Set代替大量的switchif/elseif块:

    请注意,我是如何使用Set<String>并使用.contains()对命令进行分类的,而不是庞大的switchif/elseif怪异的代码,它们会使您的代码膨胀,更重要的是使维护成为噩梦!添加新的重载命令就像将新的String添加到构造函数中的数组一样简单。

    这对于i18ni10n以及适当的ResourceBundles也可以很好地工作。Map<Locale,Set<String>>将使您以很少的开销获得多语言支持!

    @Nonnull

    我已经决定,我的所有代码都应explicitly声明是@Nonnull还是@Nullable。它可以让您的IDE帮助您警告潜在的NullPointerException危害以及何时无需检查。

    最重要的是,它记录了对 future 读者的期望,即这些方法参数都不应该是null

    调用.close()

    真正想一想,然后再做。

    如果您调用System.in,您认为sis.close()会发生什么?请参阅上面 list 中的评论。

    fork and send pull requests,我将针对其他基本用法方案更新此问题和解答。

    关于java - 如何使用java.util.Scanner从System.in正确读取用户输入并对其进行操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26446599/

    相关文章:

    java - 有没有办法在 Java 8 中使用 Streams 合并两个 for 循环?

    java - 使用 Google GSON 解析 JSON : reading values directly from child objects

    java - PostgreSQL 从数据库中获取图像

    java 不会使用 Scanner 和 System.in 分解具有多个 double 和 char 变量的用户输入

    java - 如何从 AWS 访问 RDS 数据库

    java - 将日志文件拆分为由正则表达式分隔的 block

    java - 如何在 Java 中快速搜索大文件中的字符串?

    Java 抛出 NoSuchElementException

    java - 问 : Help understanding closing Scanner