user15629312
user15629312

Reputation: 33

How to detect an empty line in java scanner

I've searched a lot but found nothing that can solve this problem. I'm using nextInt to read the input from the user, but if the user enters nothing (just presses enter), it will loop infinitely until the user enters something. But what I want is to stop the program if the user enters nothing, and tell them "this is empty". What should I do? Could someone help me please? Thanks in advance.

import java.util.Scanner;

public class Compare{
    public static void main(String[] args){

        Scanner scan = new Scanner(System.in);

        if (scan.hasNextInt()){

            int num1 = scan.nextInt();
            int num2 = scan.nextInt();

            int Difference = Math.abs(num2 - num1);

            if (num1 == num2) {
                System.out.println("They are equal");
            }else if (num1 < 0 | num2 < 0){
                System.out.println("No negative number!");
            }else{
                System.out.println("Their difference is " + Difference);
            }
        }else{
            System.out.println("Wrong! Please enter correct number");
        }
    }
}

Upvotes: 2

Views: 2633

Answers (5)

Alaa Alkheder
Alaa Alkheder

Reputation: 1

scanner.hasNext() will always be true and the loop won't end, because there is always a string input even though it is empty "".

You can use this statement: if(line.length() == 0) break;

Upvotes: 0

devReddit
devReddit

Reputation: 2947

You can take the input using scan.nextLine() and then check whether user gave an input with a correct pattern IN A SINGLE LINE. You can prompts the user to give the input in a single line separated by a space:

System.out.println("Please enter two numbers in a single line separated by a space. (i. e.: 4 12)");

You can check the pattern and do your job through split and parsing as folows:

if (Pattern.matches("\\d+ \\d+", input)) {
        String[] nums = input.split(" ");
        int num1 = Integer.parseInt(nums[0]);
        int num2 = Integer.parseInt(nums[1]);
        ....
}

The full program is as below:

public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);
    String input = scan.nextLine();
    if (Pattern.matches("\\d+ \\d+", input)) {
        String[] nums = input.split(" ");
        int num1 = Integer.parseInt(nums[0]);
        int num2 = Integer.parseInt(nums[1]);
        if (num1 == num2) {
            System.out.println("They are equal");
        } else if (num1 < 0 || num2 < 0) {
            System.out.println("No negative number!");
        } else {
            System.out.println("Their difference is " + Math.abs(num2 - num1));
        }
    } else {
        if (input.isEmpty()) {
            System.out.println("This is Empty");
        } else {
            System.out.println("Wrong! Please enter correct number");
        }
    }
}

UPDATE

If you want to make your program supportive to both single line input and double line input, you can refactor the code as follows:

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    System.out.println("Please enter two numbers in a single line separated by a space. (i. e.: 4 12)");
    String input = scan.nextLine().trim();
    if (input.matches("\\d+ \\d+")) {
        doParsingAndCalculation(input);
    } else {
        if (input.isEmpty()) {
            System.out.println("This is Empty");
        } else if (input.matches("\\d+")) {
            String secondLine = scan.nextLine().trim();
            StringBuilder stringBuilder = new StringBuilder(input);
            if(secondLine.matches("\\d+")) {
                stringBuilder.append(" ").append(secondLine);
                doParsingAndCalculation(stringBuilder.toString());
            } else {
                System.out.println("Wrong! Please enter correct number");
            }
        }
        else {
            System.out.println("Wrong! Please enter correct number");
        }
    }
}

private static void doParsingAndCalculation(String input) {
    String[] nums = input.split(" ");
    int num1 = Integer.parseInt(nums[0]);
    int num2 = Integer.parseInt(nums[1]);
    if (num1 == num2) {
        System.out.println("They are equal");
    } else if (num1 < 0 || num2 < 0) {
        System.out.println("No negative number!");
    } else {
        System.out.println("Their difference is " + Math.abs(num2 - num1));
    }
}

Upvotes: 1

melvio
melvio

Reputation: 1140

This piece of code checks if the user pressed <Enter>. If they did then we print out "User pressed enter". If they pressed something else then we attempt to parse the line as an integer.

import java.util.Scanner;

public class Play {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        // The sc.nextLine() call will retrieve 
        // the line that the user entered.
        String lineEnteredByUser = sc.nextLine();

        // If the user presses an empty line 
        // the lineEnteredByUser variable will contain 
        // the empty String "".
        if ("".equals(lineEnteredByUser)) {
            System.out.println("User pressed enter");

        } else {            
            // If the user entered something else then
            // we try to parse it as an `int` using
            // `Integer.parseInt`. A NumberFormatException
            // might occur if the use did not input an int.   
            int result = Integer.parseInt(lineEnteredByUser); 
            System.out.println("User pressed " + result);
        }
    }
}

If we run the above java code (which I placed in a file called Play.java) we get the following:

$ java Play.java
1
User pressed 1

$ java Play.java

User pressed enter

$ java Play.java
1.2
Exception in thread "main" java.lang.NumberFormatException: For input string: "1.2"

The docs for the functions that I used you can find over here: parseInt, nextLine

Upvotes: 1

Stephen C
Stephen C

Reputation: 719709

I'm using nextInt to read the input from the user, but if the user enters nothing (just presses enter), it will loop infinitely until the user enters something.

That is true, assuming that the Scanner reads from standard input. (The nextInt call will just keep reading until it gets non-whitespace characters.)

So if you want to give the user the option of typing ENTER to stop, you should not call nextInt() on the Scanner directly. Instead, you could call nextLine() to get a complete input line from the user. Then attempt to parse the line as an integer; e.g. using new Scanner(theLine).nextInt().

There are a number of possible variations on this.


If your goal is (literally) just to test for an empty line, then call Scanner.nextLine() and test if the result is an empty string. However, you need to take account of what happened to the scanner before you called nextLine(). For example, if the last thing you did was (successfully) call nextInt(), then there will still be characters after the number ... on the current line. You would need to "consume" those characters (with an extra nextLine() call) before you can read the next line.

Upvotes: 0

A Kurian
A Kurian

Reputation: 1

Scanner scanner = new Scanner(System.in);
String nextLine = scanner.nextLine() ;

you can check nextLine.equals("") is an empty string or not.

Upvotes: 0

Related Questions