HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Close Scanner if no input

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
inputclosescanner

Problem

I'm in very early stages of learning some Java coding. I'm asking for this review because, although the code below works, I'd like to know if it's an ugly way of achieving it.
What I want the code to do is take input from Scanner and reprint it, except if the input is empty, ie, just hit the return key, in which case the Scanner should close and the program end.

import java.util.Scanner;

public class Morse {

static boolean truefalse = true;

public static void main(String[] args) {
    // TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
while (truefalse)
{
String line = input.nextLine();
if (line.equals(""))
truefalse = false;
else
System.out.println(line);
}
input.close();
}

}

Solution

There are a number of ways your code can be improved:

-
Use nice indentation using 4 spaces. This improves the readability a lot. See the official guidelines on indentation here.

Basically every time you open a new curly brace you should start a new indentation depth. (See code sample below)

-
Use braces around all kinds of blocks, e.g. here even for one-lined if/else blocks. Also, for Java it is the official convention to place the braces like this:

if (line.equals("")) {
    truefalse = false;
} else {
    System.out.println(line);
}


-
You can use a trick to assign the value of the scanner input to a variable inside the while condition and then use the String's isEmpty() function to check if the input was empty. This way you can spare the boolean variable indicating whether something was read:

while (!(line = input.nextLine()).isEmpty())


-
Use try() to create instances of Types that implement java.lang.AutoCloseable to make sure they are automatically closed when the block ends (Note this only works with Java 7 or newer):

try (Scanner input = new Scanner(System.in))


See here for reference.

Putting that all together:

public class Morse {

    public static void main(String[] args) {
        try (Scanner input = new Scanner(System.in)) {
            String line;
            while (!(line = input.nextLine()).isEmpty()) {
                System.out.println(line);
            }
        }
    }
}

Code Snippets

if (line.equals("")) {
    truefalse = false;
} else {
    System.out.println(line);
}
while (!(line = input.nextLine()).isEmpty())
try (Scanner input = new Scanner(System.in))
public class Morse {

    public static void main(String[] args) {
        try (Scanner input = new Scanner(System.in)) {
            String line;
            while (!(line = input.nextLine()).isEmpty()) {
                System.out.println(line);
            }
        }
    }
}

Context

StackExchange Code Review Q#70414, answer score: 8

Revisions (0)

No revisions yet.