I've been doing a lot of programs for classes that require a prompt from the program. I thought it would be much faster for me to rapidly test inputs if I didn't have to execute the program and then type the input once inside the program (as opposed to just hitting ↑ and adjusting the input that way).
My concern is this code seems to have some duplication with the exception handling, and I'm also not sure if it's as efficient as it can be. I'm somewhat of a beginner, but I'm certainly interested in more advanced ideas/solutions as that would point in direction of where to self-study more.
import java.util.Scanner;
/*
* This program is to implement testing command line input or reverting to regular prompts if
* an argument isn't provided or is invalid. It tests to see if the input is a negative integer,
* and displays the result.
*
* Algorithm:
* If the console argument is valid, treat it as user input, or otherwise ignore it
* Continue to ask for a positive integer until one is given.
* Display the integer given and confirm it's negative
*/
public class TestConsoleArgs
{
public static void main( String[] args )
{
String arg;
Scanner user_input = new Scanner(System.in);
int num = 0;
try {
arg = args[0];
num = Integer.parseInt(arg);
} catch (ArrayIndexOutOfBoundsException e) {
arg = "";
} catch (NumberFormatException e2) {
arg = "";
}
while (num <= 0)
{
System.out.print("Please type in a positive integer. ");
arg = user_input.next();
try {
num = Integer.parseInt(arg);
} catch (NumberFormatException e) {
System.out.print("That's not an integer! ");
continue;
}
if (num <= 0)
{
System.out.print("That's a negative number. ");
}
}
System.out.println("Yes, '" + num + "' is a positive integer.");
}
}
main()
method will be of some help too... \$\endgroup\$echo foo | java MyClass
. Orjava MyClass <<< "some string"
, to make the interactive up-arrow cmdline editting slightly easier. (ctrl-a beginning of line, alt-d delete forward word would set you up for typing a new "foo" if you're using a terminal & shell with nice cmdline editing, e.g. bash. See unix.stackexchange.com/a/231671/79808 for more tips. These should work in a cygwin terminal in Windows, too, and maybe even mingw.) \$\endgroup\$