Java Lesson 2: Using the Scanner Object and Making Calculations

Key Points:

  • The Scanner object in Java lets you grab information as the user enters it via keyboard device.
  • To use the scanner object your first must import it:
    import java.util.Scanner;
  • After importing the scanner object you must declare a scanner object variable:
    Scanner keyboard = new Scanner(System.in);

    • I like using keyboard as the variable name because its easy for me to remember, but you can choose whatever you like :).
  • To use the scanner object to grab user information from a variable (in this example an integer):
    int scoreOne = keyboard.nextInt();

    • If this were a double:
      double scoreOne = keyboard.nextInt();
    • If this were a string:
      String favSeason = keyboard.next();
  • To make a calculation:
    int total = scoreOne + scoreTwo + scoreThree;
    int avg = total / 3;
  • To output the result:
    System.out.println(“Your average is: ” + avg + ” %.”);

The Code: View on GitHub