User Input

CSCI 1933 – Introduction to Algorithms and Data Structures
Adriana Picoral

Scanner

The Scanner class (from java.util) is used to get different types of input

We use System.in to read keyboard input:

Scanner myObj = new Scanner(System.in);  // Scanner object
String userInputString = myObj.nextLine();  // method to read user input
int userInputInt = myObj.nextInt(); // another method to read user input

Scanner has a few methods to read input besides .nextInt()

out and in are public static final variables in System

Adding Scanner to Calculator

Remember to print out messages to the user.

public static void main(String[] args) {
  Scanner scanner = new Scanner(System.in);
  System.out.print("Enter a number: ");
  double left = scanner.nextDouble();
  System.out.print("Enter another number: ");
  double right = scanner.nextDouble();
  Calculator calc = new Calculator(left, right);
  System.out.println(calc);
}

What happens if the user does not enter a number?

Practice

Write a Java application to check if a year is leap or regular. Leap years are those that are either:

  • divisible by 4 and not 100
  • divisible by 400

Write a main static method in the same class that asks for user input, and prints out a message saying whether the year entered is leap or not.

Submit your LeapYear.java file with a static isLeap(int year) that returns either "Leap Year" or "Regular Year" to Gradescope.