Reading multiple lines into a scanner object in Ja

2019-04-03 01:21发布

问题:

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

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.

Thanks!

回答1:

Using 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);

Or using Scanner:

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

For both cases, Sample I/O:

Welcome to Stackoverflow
Hello My friend
Its over now

Welcome to Stackoverflow
Hello My friend
Its over now

Complete code

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