在java中获取输入 [英] Getting input in java

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

问题描述

我想在输入时从控制台获取输入。
现在我的代码是:

I wanna to get input from console while it has input. Now my code is this:

Scanner scan = new Scanner(System.in);
String word = "s";
while (word.length() > 0) {
    word = scan.nextLine();
    if (!word.equals(""))
        t.addWord(word);
}

但在某些情况下它会给我没有这样的元素异常。我不知道导致问题的原因是什么,因为其他人检查我的代码。

but in some cases it gives me no such element exception . I don't know what is the case that cause the problem,because somebody else checks my code.

我也检查了 hasNext 在我的条件下。
它运作错误

also I checked hasNext in my while condition. it works wrong

String word;
while (scan.hasNextLine()) {
    word = scan.nextLine();
    t.addWord(word);
}

我该怎么办?我的问题是什么?

what should I do? what is my problem?

推荐答案

你的第二个代码剪断不会对 word执行相同的长度检查和第一个代码段一样。假设你希望终止while循环,如果 word 只是一个空行,那么如果满足这个条件,则放置一个会突破循环的条件:

Your second code snipped does not perform the same length check on word as does the first code snippet. Presuming you wish to terminate the while loop if word is just an empty line, then place a condition that will breaks out of the loop if this condition is met:

while ( scan.hasNextLine() ){
    word = scan.nextLine();
    if ( word.length() > 0 ){
        t.addWord(word);
    }else{
        break;
    }
}

这篇关于在java中获取输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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