0

I need to get multiple line Input from a User in Java. Currently I'm using the Scanner class to get the input, but the loop I'm using to check each line does not break.

Current Code

package getxml;

import java.util.Scanner;


public class Test{

    public static void main(String[] args) {
          
    System.out.println("Enter the Codes: ");   
    Scanner in = new Scanner(System.in);
    
    while(in.hasNextLine()) {
        String nextLine = in.nextLine();
        System.out.println("nextLine:" + nextLine);
    }   
    in.close();
    System.out.println("Scanner closed");
    }
}

Expected Input

10229892
10120470
10295277
10229618
10229643
10229699

Expected Output

nextLine:10229892
nextLine:10120470
nextLine:10295277
nextLine:10229618
nextLine:10229643
nextLine:10229699
Scanner closed

Real Output

nextLine:10229892
nextLine:10120470
nextLine:10295277
nextLine:10229618
nextLine:10229643
nextLine:10229699

I have tried changing the

hasNextLine() 

to

hasNext() 

And adding a If condition to break out of the loop with following logic:

if (nextLine.equals("")) {
    in.close();
    System.out.println("bye");
    break;
}

I need to secure the in.nextLine() to a variable, otherwise it will iterate 2 lines in one loop.

3 Answers 3

1

First you will have to decide what is going to be considered The End Of User Input and then act upon that specific condition. In the little example below, if the User enters nothing then that will be considered the End Of User Input.

All the code numbers entered by the User are stored within a List Interface object. Rules have also been applied whereas all code numbers supplied must be numerical and eight digits in length. The String#matches() method is used for this along with a small Regular Expression (regex). Also, there can be no duplicate code numbers supplied, each code number must be unique.

When the User has finished entering the desired Code Numbers then those numbers are sorted in ascending order and displayed within the console window:

System.out.println("Enter the required code numbers (enter nothing when done): ");   
Scanner in = new Scanner(System.in);

List<String> codes = new ArrayList<>();
// Outer loop to keep asking for Code Numbers
while (true) {
    boolean isValid = false; // Flag to ensure a valid entry
    String codeLine = "";
    // inner loop to back up valitity before storing supplied code Number.
    while (!isValid) {    
        System.out.print("Code Line: --> ");
        codeLine = in.nextLine().trim();
        // Break out of this inner loop if nothing is supplied
        if (codeLine.isEmpty()) { break; } 
        // Is the supplied number all digits and are there 8 of them? 
        if (!codeLine.matches("^\\d{8}$")) {
            // No...
            System.err.println("Invalid Code Number! Try Again...");
        }
        // Has the supplied number already been previously stored?
        // In other words, is it unique?
        else if (codes.contains(codeLine)) {
            // Already got it! Not Unique!
            System.err.println("Code Number: " + codeLine + " has already been supplied!");
        }
        // Passed validity! Set isValid to true so to exit this inner loop.
        else { isValid = true; }
    }
    // Break out of the outer loop is nothing was supplied.
    if (codeLine.isEmpty()) { break; }
        
    // Validity has been met so Store the the supplied code number.
    codes.add(codeLine);
}
in.close(); // Close the input Stream
System.out.println("Scanner closed");
    
// Sort the Stored Code Numbers in ascending order.
Collections.sort(codes);
    
// Display the Stored Code Numbers...
System.out.println("Code Numbers Entered:");
System.out.println(codes);
Sign up to request clarification or add additional context in comments.

Comments

1

The issue is that your code does not know if the user has stopped entering the codes.

You can do something like this :

public static void main(String[] args) {

    System.out.println("Enter the Codes: ");

    Scanner in = new Scanner(System.in);
    String nextLine = "";
    do{
        nextLine = in.nextLine();
        System.out.println("nextLine:" + nextLine);
    } while(!nextLine.equals("exit"));

    in.close();


    System.out.println("Scanner closed");
}

And you console will look like:

enter image description here

3 Comments

I'm trying to make java detect the "end of input" by itself, instead of coding a "end-word" in.
@Reachyy That's not working using System.in. It's a infinite source of input data and you dont know where is the end. You can change it by counter, endword, single-enter press, ... but System.in will always continue listening to the next input or bevaving like there is more. In comparison: Reading a file from start to end you can use hasNextLine() and stop then. That's a limited source.
@LenglBoy I had a feeling that System.in might always be listening. Thank you for clarifying! +
0

"Enter" is end of input. What you are trying to do is simulate or work around that. If your objective is to just simulate multiline input, following should work:

    public static void main(String[] args) {

        System.out.println("Enter the Codes: ");   
        Scanner in = new Scanner(System.in);
        
        String allLines = "";
        while(in.hasNextLine()) {
            String nextLine = in.nextLine().trim();
            if (nextLine.isEmpty() || nextLine.equals("\r") || nextLine.equals("\r\n") || nextLine.equals("\n")) {
                break;
            }
            allLines += "\r\n" + nextLine;
            //System.out.println("nextLine:" + nextLine);
        }
        System.out.println("all lines:" + allLines);
        in.close();
        
        System.out.println("Scanner closed");
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.