javaconsolelines

Read multiple lines from console in Java, issue with last line


I want to load multiple lines from console. I paste text into console, this text has more lines. Last line doesn't want to load, its because there is missing \n. I am not able to add \n in console, because when I paste it, it runs immediately. Another issue is that while doesn't want to end. It loads everything expect last line and doesn't end.

        Scanner input = new Scanner(System.in); 
        List<String> lines = new ArrayList<String>();
        String lineNew;

        while (input.hasNextLine()) {
            lineNew = input.nextLine();
            System.out.println(lineNew);
            lines.add(lineNew);         
        }

Solution

  • You could just add a check if your input is too short and if yes, break.

    import java.util.ArrayList;
    import java.util.List;
    import java.util.Scanner;
    
    public class Lines {
        public static void main(String[] args) {
    
            Scanner input = new Scanner(System.in);
            List<String> lines = new ArrayList<String>();
            String lineNew;
    
            while (input.hasNextLine()) {
                lineNew = input.nextLine();
                if (lineNew.isEmpty()) {
                    break;
                }
                System.out.println(lineNew);
                lines.add(lineNew);
            }
    
            System.out.println("Content of List<String> lines:");
            for (String string : lines) {
                System.out.println(string);
            }
        }
    }