第1章課後作業
第1題 編寫一個計算器類
public class Calculator {
int num1;
int num2;
double result;
String operation;
public void show() {System.out.println(result);
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Calculator calculator = new Calculator();
System.out.println("請輸入算式(中間用空格隔開):");
calculator.num1 = input.nextInt();
calculator.operation = input.next();
calculator.num2 = input.nextInt();
switch (calculator.operation) {
case "+":
calculator.result = calculator.num1 + calculator.num2;
break;
case "-":
calculator.result = calculator.num1 - calculator.num2;
break;
case "*":
calculator.result = calculator.num1 * calculator.num2;
break;
case "/":
calculator.result = calculator.num1 / (calculator.num2 * 1.0);
break;
}
calculator.show();
}
}
第2題 編寫時間的類
public class CurrentTime {
int year=2015;
int moth=5;
int day=12;
int hour=10;
int minutes=11;
String second="00";
public void show() {System.out.println("現在時間是:"+year+"年"+moth+"月"
+day+"日"+hour+"點"+minutes+"分"+second+"秒");
}
}
public static void main(String[] args) {
CurrentTime currentTime = new CurrentTime();
currentTime.show();
}
第3題 改進上一題改變設定的時間
public class Demo {
public static void main(String[] args) {
CurrentTime current = new CurrentTime();
current.year = 2018;
current.second = "50";
current.show();
}
}
第4題 使用類描述計算機
public class Computer {
String cpu = "CPU";
String mainBoard = "主機板";
String monitor = "顯示器";
String hardDisk = "硬碟";
String Memory = "記憶體";
public void showInfo() {
System.out.println("計算機的主要部件有:"+cpu + " " + mainBoard + " " + monitor + " " + hardDisk + " " + Memory);
}
}
public static void main(String[] args) {
Computer info = new Computer();
info.showInfo();
}
}
第5題 開發遊戲,編寫一些類
public class Hero {
String heroName = "李小俠";
int heroLifeValue = 300;
public void show() {
System.out.println("我是英雄,我的基本資訊如下:");
System.out.println("姓名:" + heroName + ",生命值:" + heroLifeValue);
}
}
public class Monster {
String monsterName = "小龜";
int monsterLifeValue = 300;
String type = "潛水類";
public void show() {
System.out.println("我是怪物,我的基本資訊如下:");
System.out.println("姓名:"+monsterName+",生命值:"+monsterLifeValue+",型別:"+type);
}
}
public class Weapons {
String weaponsName = "死神鐮刀";//武器名字
int aggressivity = 999;//攻擊力
public void show() {
System.out.println("我是武器,我的基本資訊如下:");
System.out.println("武器名:"+weaponsName+",攻擊力:"+aggressivity);
}
}
public static void main(String[] args) {
Hero hero = new Hero();
Monster monster = new Monster();
Weapons weapons = new Weapons();
hero.show();
weapons.show();
monster.show();
}
}