There are many ways to get user input from the console. The following is just one of them.
We can use the readLine() method get the user input, it is returned as a String.
String name = System.console().readLine();
As mentioned above, readLine() returns a String, if you want the input as a number, it will need to be converted. Integer.parseInt(age) can be used to do this, if it fails it will trigger an exception.
try{ int num=Integer.parseInt("10"); }catch(Exception e){ System.out.println("Hmmm... That did not work"); }
The catch part is where you should handle what you program will do if the input is not correct.
With the Java JDK installed, from a command line:
class Morning{ public static void main(String[] args){ System.out.print("What is your name? "); String name = System.console().readLine(); System.out.println("Good morning "+name+"!"); System.out.print("What is your age? "); String age = System.console().readLine(); try{ int num=Integer.parseInt(age); System.out.print("You were probably born in "+(2025-num) ); }catch(Exception e){ System.out.println("Hmmm... That does not seem like an age?"); } } }
Created (04/05/2025)