Accepting User Input in Java

First, let's take a look at a simple "Hello, world!" program from last time.
  1. public class hello
  2.  
  3. {
  4.  
  5. public static void main(String[] args)
  6.  
  7. {
  8.  
  9. System.out.println("Hello, world!");
  10.  
  11. }
  12.  
  13. }
You don't need to know what everything means in order to get the program running, but it is a good idea to know some terms for more advanced programming later on. public (as opposed to private) - this method can be called from outside the class. static - this means that the method cannot be called (made to run) by another method. void - this method does not return any value to another method once it runs. main - the main method and is needed for any Java application to run. Don't worry if you can't remember all of that now! It would just be good to reference later on when our programs begin to use more methods. What if you don't want to say hello to the whole world? What if you just want to say hello to the person using the program? We can make that possible by adding a couple lines of code to our program. Comments will only be placed on new/altered lines of code:
  1. import java.util.Scanner; //imports the scanner method, making it possible to use later on for user input
  2.  
  3. public class greeting
  4. {
  5.  
  6. public static void main(String[] args)
  7.  
  8. {
  9.  
  10. Scanner input = new Scanner(System.in); //this creates a scanner object which reads the user's input
  11.  
  12. System.out.print("What is your name? "); //this asks the user for their name. a space is left after the question mark for neatness
  13.  
  14. String name = input.nextLine(); //this takes the user's input, and assigns it to a new variable called name. string variables are made up of any collection of characters
  15.  
  16. System.out.println("Hello, " + name + "!"); //this replaces "world" with the user's name. note the + signs here. they connect variables and quoted text, allowing them to be used together.
  17.  
  18. }
  19.  
  20. }
Save the code as greeting.java, and run it according to the first tutorial.

Add new comment