Reading multiple lines into a scanner object in Java

后端 未结 1 1304
走了就别回头了
走了就别回头了 2021-01-01 07:51

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:

相关标签:
1条回答
  • 2021-01-01 08:40

    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;
    }
    
    0 讨论(0)
提交回复
热议问题