2.6 Lab - Console Input in Java

Introduction

In this lab, you will learn how to handle user input in Java through the console using the Scanner class. Console input is a fundamental skill in programming, as it allows your Java programs to interact with users by accepting data at runtime. You will use the Nano editor in a Linux environment to write a Java program that takes user input, processes it, and displays the result.

Objectives

By the end of this lab, you will be able to:

  1. Use the Scanner class to read input from the console.
  2. Write Java programs that prompt users for input.
  3. Handle basic input types such as strings and integers.
  4. Compile and run Java programs that accept console input.

Lab Steps

Step 1: Access the Linux Terminal
  1. Open the terminal on your Linux system.
  2. Ensure you are in your home directory by running the command:
    cd ~
    
Step 2: Create and Edit a Java File
  1. Create a new Java file named ConsoleInput.java using the Nano editor:
    nano ConsoleInput.java
    
  2. Type the following Java code into the file to prompt the user for their name and age:
    import java.util.Scanner;
    
    public class ConsoleInput {
        public static void main(String[] args) {
            // Create a Scanner object to read input
            Scanner scanner = new Scanner(System.in);
    
            // Prompt the user for their name
            System.out.print("Enter your name: ");
            String name = scanner.nextLine();
    
            // Prompt the user for their age
            System.out.print("Enter your age: ");
            int age = scanner.nextInt();
    
            // Display the input back to the user
            System.out.println("Hello, " + name + "! You are " + age + " years old.");
        }
    }
    
  3. Save the file by pressing CTRL + O, then hit Enter to confirm the filename.
  4. Exit Nano by pressing CTRL + X.
Step 3: Compile the Java Program
  1. In the terminal, compile the Java program using the javac command:
    javac ConsoleInput.java
    
  2. If there are no errors, this command will create a file named ConsoleInput.class. Verify this by running:
    ls
    
Step 4: Run the Java Program
  1. Run the compiled program using the java command:
    java ConsoleInput
    
  2. The program will prompt you to enter your name and age. For example:
    Enter your name: John
    Enter your age: 25
    
  3. The program will output:
    Hello, John! You are 25 years old.
    
Step 5: Modify the Program
  1. Open the ConsoleInput.java file again using Nano:
    nano ConsoleInput.java
    
  2. Modify the program to ask for additional input, such as the user’s favorite color:
    System.out.print("Enter your favorite color: ");
    String color = scanner.next();
    
    // Display the additional input back to the user
    System.out.println(name + ", you are " + age + " years old and your favorite color is " + color + ".");
    
  3. Save, exit, recompile, and run the program again to see the updated output:
    javac ConsoleInput.java
    java ConsoleInput
    
Step 6: Handle Different Input Types
  1. Modify the program to ask for the user’s height (in meters) and handle it as a floating-point number:
    System.out.print("Enter your height in meters: ");
    double height = scanner.nextDouble();
    
    // Display the height back to the user
    System.out.println("You are " + height + " meters tall.");
    
  2. Save, exit, recompile, and run the program again to test the input of different data types:
    javac ConsoleInput.java
    java ConsoleInput
    
Step 7: Experiment with Error Handling (Optional)
  1. Try running the program and entering an invalid input for the age (e.g., typing a string instead of a number).
  2. Observe the error message. You can extend the program later to handle invalid inputs using try-catch blocks.
Step 8: Cleanup (Optional)
  1. Once you are done with the lab, clean up the directory by removing the .class files:
    rm *.class
    

Summary

In this lab, you learned how to use the Scanner class to accept user input from the console in Java. You wrote a program that prompts the user for their name, age, and other information, processes this input, and displays it back to the user. You also explored handling different data types such as strings, integers, and floating-point numbers. Handling user input is an essential aspect of making your Java programs interactive and dynamic.