I'm a newcomer to Java (I primarily do C# ) and I have to say that they have made I/O handling much more difficult than it should have been. I am accustomed to the scenario where when I need keyboard input in a class of my application I simply call Console.Readline()
and does the job. In Java, I must create a Scanner object in order to perform these operations and when input is needed in methods of different classes things get more complicated. So what I thought was creating an Input class where all keyboard inputs are handled there.
import java.time.* ;
import java.time.format.DateTimeParseException;
import java.util.Scanner;
public class Input
{
private static Scanner scan = new Scanner(System.in);
public static void UseEnterAsDelimiter()
{
scan.useDelimiter(System.getProperty("line.separator"));
}
public static int IntInRange(int min , int max, String InvalidMsg )
{
int value;
while(true)
{
while (!scan.hasNextInt())
{
System.out.println("Expected an Integer. Please type again.");
scan.next();
}
value = scan.nextInt();
if( value >= min && value <= max)
return value;
else
{
System.out.println(InvalidMsg);
}
}
}
public static int Int()
{
int value;
while (true)
{
while (!scan.hasNextInt())
{
System.out.println("Expected an Integer. Please type again.");
scan.next();
}
value = scan.nextInt();
return value;
}
}
public static String String()
{
return scan.next();
}
public static String StringNoEmpty()
{
String value;
while(true)
{
value = scan.next();
if ( !value.isEmpty())
return value;
else
System.out.println("Input cannot be blank. Please type again.");
}
}
public static LocalDate Date()
{
LocalDate value;
while(true)
{
try
{
String input = scan.next();
if( input.isEmpty())
System.out.println("Field cannot be empty.");
else
{
value = LocalDate.parse(input);
return value;
}
}
catch(DateTimeParseException e)
{
System.out.println("Date was not given in a correct format , please type it again.");
}
}
}
public static LocalTime Time()
{
LocalTime value;
while(true)
{
try
{
String input = scan.next();
if( input.isEmpty())
System.out.println("Field cannot be empty.");
else
{
value = LocalTime.parse(input);
return value;
}
}
catch(DateTimeParseException e)
{
System.out.println("Time was not given in a correct format , please type it again.");
}
}
}
public static void CloseScanner()
{
scan.close();
}
}
My question is if it's considered good practice to use a static Scanner and if it is what can I do to make this class better. I'm looking for improvement here, this class does what's expected but I don't know if it's the correct way.