在Java中将多行读入扫描仪对象 [英] Reading multiple lines into a scanner object in Java

查看:145
本文介绍了在Java中将多行读入扫描仪对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在弄清楚如何将多行用户输入读入扫描仪然后将其存储到单个字符串中时遇到了一些麻烦。
我到目前为止的内容如下:

I'm having a bit of trouble figuring out how to read multiple lines of user input into a scanner and then storing it into a single string. What I have so far is down below:

public static String getUserString(Scanner keyboard) { 
    System.out.println("Enter Initial Text:");
    String input = "";
    String nextLine = keyboard.nextLine();
    while(keyboard.hasNextLine()){
        input += keyboard.nextLine
    };
    return input;
}

然后主要方法的前三个语句是:

then the first three statements of the main method is:

Scanner scnr = new Scanner(System.in);
String userString = getUserString(scnr);  
System.out.println("\nCurrent Text: " + userString );

我的目标是让用户输入文字时,只需点击即可为他们输入的所有内容输入两次以显示回来(在当前文字:之后)。另外我需要将字符串存储在main中的变量userString中(我必须在其他方法中使用此变量)。任何有关这方面的帮助将非常感谢。它是类,我们不能使用数组或Stringbuilder或任何比while循环和基本字符串方法复杂得多的东西。

My goal is to have it where once the user types their text, all they have to do is hit Enter twice for everything they've typed to be displayed back at them (following "Current text: "). Also I need to store the string in the variable userString in the main (I have to use this variable in other methods). Any help at all with this would be very much appreciated. It's for class, and we can't use arrays or Stringbuilder or anything much more complicated than a while loop and basic string methods.

谢谢!

推荐答案

使用 BufferedReader

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = "";
String line;
while((line = br.readLine()) != null){
    if(line.isEmpty()){
        break; // if an input is empty, break
    }
    input += line + "\n";
}
br.close();
System.out.println(input);

或使用扫描仪

String input = "";
Scanner keyboard = new Scanner(System.in);
String line;
while (keyboard.hasNextLine()) {
    line = keyboard.nextLine();
    if (line.isEmpty()) {
        break;
    }
    input += line + "\n";
}
System.out.println(input);

对于这两种情况,样本I / O:

For both cases, Sample I/O:

Welcome to Stackoverflow
Hello My friend
Its over now

Welcome to Stackoverflow
Hello My friend
Its over now

完整代码

public static void main (String[] args) {
    Scanner scnr = new Scanner(System.in);
    String userString = getUserString(scnr);  
    System.out.println("\nCurrent Text: " + userString);
}

public static String getUserString(Scanner keyboard) { 
    System.out.println("Enter Initial Text: ");
    String input = "";
    String line;
    while (keyboard.hasNextLine()) {
        line = keyboard.nextLine();
        if (line.isEmpty()) {
            break;
        }
        input += line + "\n";
    }
    return input;
}

这篇关于在Java中将多行读入扫描仪对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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