使用扫描程序从Java中读取控制台

时间:2015-03-05 21:24:06

标签: java string java.util.scanner

我尝试使用Scanner从控制台读取字符串对象并继续添加数据,直到用户按两次输入。我如何改进代码?

    String text;

public void Settext() {

    System.out.println("please enter the values for the text :");
    String S;

    Scanner scn = new Scanner(System.in);
    if ((S = scn.next())!= null) {
        text += S.split("\\|");
    }
    scn.close();
}

public String toString() {
    Settext();
    String S = "the output of document class toString method is " + text;

    return S;
}

2 个答案:

答案 0 :(得分:0)

使用此代替if语句 -

int noOfNulls = 0;
while(noOfNulls != 2)
{
    if ((S = scn.next()) != null)
    {
        text += S.split("\\|");
        noOfNulls = 0;
    }
    else
        noOfNulls++;
}

答案 1 :(得分:0)

我认为这可能会对你有所帮助。你描述的是什么考虑到用户可能会多次按Enter键但不能连续按下。

Scanner scanner = new Scanner(System.in);
            String readString = scanner.nextLine();
            String buffer="";
            boolean previusEnter=false;
            while(readString!=null) {


                if (readString.equals("")){
                    if(previusEnter)
                        break;
                    previusEnter=true;
                }
                else
                    previusEnter=false;

                buffer+= readString+"\n";

                if (scanner.hasNextLine())
                    readString = scanner.nextLine();                                   
                else
                    readString = null;
            }