在Java

时间:2017-02-24 01:18:59

标签: java string class

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

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;
}

然后主要方法的前三个陈述是:

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

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

谢谢!

1 个答案:

答案 0 :(得分:3)

使用 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:

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;
}