使用Scanner.next()获取文本输入 [英] Using Scanner.next() to get text input

查看:48
本文介绍了使用Scanner.next()获取文本输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Java 6从键盘获取文本输入.我是该语言的新手,只要运行以下代码,就会出现此错误:

I am trying to get text input from the keyboard in Java 6. I am new to the language and whenever i run the following code, I get this error:

package test1;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
    boolean quit = false;
    while (!quit){
        Scanner keyIn;
        String c = "x";
        while (c != "y" && c != "n") {
            keyIn = new Scanner(System.in);
            c = keyIn.next();
            keyIn.close();
        }
        if (c == "n")
            quit = true;
    }
 }
}


Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:838)
at java.util.Scanner.next(Scanner.java:1347)
at test1.Test.main(Test.java:11)

我误用next()方法了吗?我以为它会等待用户输入,但看起来好像不是,并抛出异常,说扫描仪中什么也没剩下.

Am I mis-using the next() method? I thought it would wait for user input but it looks like it isn't and throwing the exception saying that there is nothing left in the scanner.

推荐答案

出现此异常的原因是您使用扫描仪一次后正在调用keyIn.close(),这不仅会关闭Scanner,还会关闭System.in .在下一个迭代中,您将创建一个新的Scanner,由于System.in现在已关闭,因此该新命令立即崩溃.要解决此问题,您应该做的只是在进入while循环之前创建一次扫描程序,并且由于不想关闭System.in而完全跳过close()调用.

The reason for the exception is that you are calling keyIn.close() after you use the scanner once, which not only closes the Scanner but also System.in. The very next iteration you create a new Scanner which promptly blows up because System.in is now closed. To fix that, what you should do is only create a scanner once before you enter the while loop, and skip the close() call entirely since you don't want to close System.in.

修复了由于==!=字符串比较而导致程序仍然无法运行的问题.在Java中比较字符串时,必须使用equals()比较字符串内容.当您使用==!=时,您正在比较对象引用,因此这些比较将始终在您的代码中返回false. 始终使用equals()比较字符串.

After fixing that the program still won't work because of the == and != string comparisons you do. When comparing strings in Java you must use equals() to compare the string contents. When you use == and != you are comparing the object references, so these comparisons will always return false in your code. Always use equals() to compare strings.

while (!quit){
    Scanner keyIn = new Scanner(System.in);
    String c = "x";
    while (!c.equals("y") && !c.equals("n")) {
        c = keyIn.next();
    }
    if (c.equals("n"))
        quit = true;
}

这篇关于使用Scanner.next()获取文本输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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