public class Person{
public int ageYears = 32;
public void calculateAge(){
int ageDays = ageYears * 365;
long ageSeconds = ageYears * 365 * 24L * 60 * 60;
System.out.println("You are " + ageDays + " days old.");
System.out.println("You are " + ageSeconds + " seconds old.");
}
}
執行它:
public class PersonDemo{
public static void main(String[] args){
Person peter = new Person();
peter.calculateAge();
}
}
配合 java.util.Scanner 物件來做為輸入數量的參考:
import java.util.Scanner;
public class Demo{
public static void main(String[] args){
Shirt myShirt = new Shirt();
myShirt.shirtID = 100;
myShirt.colorCode = 'B';
myShirt.price = 45.12;
myShirt.description = "45周年紀念衫";
myShirt.displayInformation();
Scanner scanner = new Scanner(System.in);
System.out.print("請輸入購買件數:");
int input = scanner.nextInt();
System.out.println("總價:" + input*myShirt.price);
}
}