Print Page Print Page

CH3 – Inches To Centimeters

  1. Create a new class named InchesToCentimeters. Be certain the file’s name is InchesToCentimeters.java.
  2. Type the following code and then save.
public class InchesToCentimeters {
  static int inch;
  static double cm;

  public static void main(String[] args){
    Scanner in = new Scanner(System.in);
    System.out.print("How many inches? ");
    InchesToCentimeters.inch = in.nextInt();
    cm = inch * 2.54;
    System.out.print(inch + " in =");
    System.out.println(cm + " cm");
  }
}
  1. Attempt to compile and note the exceptions.
$ javac InchesToCentimeters.java
InchesToCentimeters.java:8: error: cannot find symbol
    Scanner in = new Scanner(System.in);
    ^
  symbol:   class Scanner
  location: class InchesToCentimeters
InchesToCentimeters.java:8: error: cannot find symbol
    Scanner in = new Scanner(System.in);
                     ^
  symbol:   class Scanner
  location: class InchesToCentimeters
2 errors
  1. The compiler cannot find the Scanner class. To fix this you need to import it; however, what package does it belong to? Type the following URL in a web browser.
http://docs.oracle.com/javase/8/docs/api/
  1. Scroll the bottom left window, find the Scanner class and click on the link. Note the class is in the java.util package.

  1. Open InchesToCentimeters.java and add the following line to import the Scanner class.
import java.util.Scanner;
  1. Compile the program and run the program.
$ javac InchesToCentimeters.java
$ java InchesToCentimeters
How many inches? 12
12 in =30.48 cm