CSc 2010: PRINCIPLES OF COMPUTER SCIENCE

  

Week 1 Lab

Set up Java environment

  • Download Java JDK ( Java SE Download)
  • Install JDK in a directory of your choice.
  • Add the path of JDK (xxx\jdk1.6.0_22\bin, where xxx is the directory of your jdk) to your PATH environment variable:
  • For Windows 2000/XP: Windows 2000/XP
  • For Windows 7: Windows 7
  • For Mac: Mac

Download and Install Eclipse IDE

A Simple Java Program

// Displays the message " Hello World!"
public class HelloWorld {
  public static void main(String[] args) {
    System.out.println(" Hello World!");
  }
} 

Reading Input from Keyboard (using Scanner)

A simple text scanner which can parse primitive types and strings using regular expressions. A scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.

Program to read input from keyboard and output result to screen

import java.util.Scanner;
public class ScanProgram1 {
  public static void main(String args[]) {
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter your name: ");
    String name = sc.nextLine();
    System.out.println("Hello, your name is "+name);
  }
}

Another program to read input from keyboard and output result to screenn

import java.util.Scanner;
public class ScanProgram2 {
  public static void main(String args[]) {
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter a whole number: ");
    int num1 = sc.nextInt();
    System.out.print("Enter another whole number: ");
    int num2 = sc.nextInt();
    int result = num1+num2;
    System.out.println("The sum of "+num1+" and "+num2+" is "+result);
  }
}

To read a decimal number, use:

double d = sc.nextDouble();

Essential Eclipse Shortcuts

Eclipse Shortcuts