首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在获取和返回用户输入方面比util.Scanner更好的选项

在获取和返回用户输入方面比util.Scanner更好的选项
EN

Stack Overflow用户
提问于 2018-09-25 01:37:40
回答 2查看 880关注 0票数 0

多亏了这里的一些反馈,我花了一些时间研究util.Scanner。让我印象最深刻的一句话是在How to use java.util.Scanner to correctly... 上的这篇文章中

你可能永远不会真正看到扫描仪在专业/商业应用程序中使用,因为它所做的每一件事都被其他东西做得更好。现实世界中的软件必须比Scanner允许你编写代码更具弹性和可维护性。现实世界中的软件使用标准化的文件格式解析器和文档化的文件格式,而不是在独立任务中给出的即席输入格式。

因此,我查找了一些获取用户输入的其他选择,并决定使用BufferedReader。我试图完成的是让用户告诉程序他们是否想继续玩游戏,让程序重复这个问题,直到给出有效的输入(Y/N),并让程序根据答案继续或终止。

三个相关问题:

BufferedReader是比扫描仪更好的选择吗?

有没有更好地解决这项任务的选择?如果是这样的话,是什么?

如果答案不符合条件,让方法调用自身来创建“循环”是否合适?

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class RageGame {

public static void main(String[] args) throws IOException  {

    char playAgain = 'Y';

    // Loop game until user decides they are done.
    do { 
        playAgain = playRage();

    } while (playAgain == 'Y');

    //Quit message      
    System.out.println("Thanks for playing Rage!");

}

public static char playRage() throws IOException {

    return playAgain();
}
public static char playAgain() throws IOException{
    char answer;

    BufferedReader kb = new BufferedReader(new InputStreamReader(System.in));

    //Ask the user if they want to continue and set their response to upper case.
    System.out.println("Do you wish to play again? (y/n)");
    answer = (char) Character.toUpperCase(kb.read());

    //Check if answer fits criteria
        if (answer != 'Y' && answer != 'N') {
            System.out.println("Sorry, " + answer + " is not a valid answer.");
            return playAgain();

        }else {
        return answer;


        }
    }
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-09-25 01:50:45

简短的答案是:不要关闭它。

您的Scanner正在使用流System.inSystem.in不是您的程序获取的资源(您没有打开流),所以您不应该关闭它。另一个人负责关闭它。

如果你觉得这个警告很烦人,你可能可以让它安静下来。

假设您的扫描器从文件中获取输入,而不是System.in,那么您需要在最后一次需要它之后调用close

answer = Character.toUpperCase(kb.next().charAt(0)); 
kb.close();

如果您害怕忘记调用close,只需使用try-with-resources块,它将为您关闭它!

try (Scanner kb = new Scanner(some other source)) {
    System.out.println("Do you wish to play again? (y/n)");
    answer = Character.toUpperCase(kb.next().charAt(0)); 
} // this will always close the scanner
票数 1
EN

Stack Overflow用户

发布于 2018-09-25 01:59:59

另一种方法是,如果您想关闭扫描仪,可以将System.in包装在CloseShieldInputStream中。您的扫描仪将使用代理流。如果你感兴趣,可以看看http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/input/CloseShieldInputStream.html

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52484598

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档