Read input line by line

前端 未结 3 1403
面向向阳花
面向向阳花 2021-02-18 22:59

How do I read input line by line in Java? I searched and so far I have this:

import java.util.Scanner;

public class MatrixReader {
    public static void main(S         


        
相关标签:
3条回答
  • 2021-02-18 23:38

    Try using hasnextLine() method.

    while (input.hasnextLine()){
    
    
        System.out.print(input.nextLine());
    
    
     }
    
    0 讨论(0)
  • 2021-02-18 23:39

    The previously posted suggestions have typo (hasNextLine spelling) and new line printing (println needed each line) issues. Below is the corrected version --

    import java.util.Scanner;
    
    public class XXXX {
        public static void main(String[] args) {
            Scanner input = new Scanner(System.in);
            while (input.hasNextLine()){
                System.out.println(input.nextLine());
            }
        }
    }
    
    0 讨论(0)
  • 2021-02-19 00:01

    Ideally you should add a final println() because by default System.out uses a PrintStream that only flushes when a newline is sent. See When/why to call System.out.flush() in Java

    while (input.hasNext()) {
        System.out.print(input.nextLine());
    }
    System.out.println();
    

    Although there are possible other reasons for your issue.

    0 讨论(0)
提交回复
热议问题