Java Methods for User Input

Nov 17, 2024

Lecture Notes: Methods in Java

Overview

  • Introduction to creating methods in Java.
  • Exercise focused on writing methods to get user input: name and age.

Getting Started

  • Task: Write a method to get the user's name and another to get the user's age.
  • Suggested to pause the video and try the exercise.

Method: getName

  • Declaration:
    • public static String getName()
  • Steps:
    1. Create a Scanner object to read user input:
      Scanner input = new Scanner(System.in);  
      
    2. Read the user's name:
      String name = input.nextLine();  
      
    3. Return the name:
      return name;  
      

Alternate Code Implementation

  • Return the result directly without storing in an intermediate variable:
    return new Scanner(System.in).nextLine();  
    
  • Note: If using an object only once, instantiate it directly in the return statement.

Using getName in main Method

  • Prompt user for input:
    System.out.print("Enter your name:");  
    System.out.println(getName());  
    
  • The method will create a Scanner, read input, and print the name back to the user.

Method: getAge

  • Declaration:
    • public static double getAge()
  • Steps:
    1. Create a new Scanner object to read user input:
      return new Scanner(System.in).nextDouble();  
      

Using getAge in main Method

  • Prompt user for age:
    System.out.print("Enter your age:");  
    
  • Concatenate user name and age for output:
    System.out.println(getName() + " " + getAge());  
    

Conclusion

  • Demonstrated methods to read user input for name and age in Java.
  • Encouraged to try running the program and observe the output.
  • Thanks for watching and looking forward to the next video.