# 數二乙物件導向程式設計(20220923)
### 數二乙 S1022106 鄭詠軒
1. [Application]利用Java的Scanner類別物件輸入並利用System靜態類別輸出。撰寫一程式輸入兩正整數a,b,求最大公因數。
```java=
import java.util.Scanner;
class HW1 {
int a, b;
HW1(){
Scanner sc = new Scanner(System.in);
a = sc.nextInt();
b = sc.nextInt();
System.out.println(GCD(a,b));
}
public int GCD(int a, int b){
if (a > b) {
if (a % b == 0)
return b;
else {
return GCD(b, a % b);
}
} else {
return GCD(b,a);
}
}
}
public class Example1 {
public static void main(String[] args){
HW1 ex= new HW1();
}
}
```
2. [Application]利用Java的Random類別物件產生電腦亂數。撰寫一程式利用電腦亂數輸出10組0~100的正整數。
```java=
import java.util.Random;
class HW2 {
HW2(){
Random r = new Random();
for (int i = 0; i < 10; i++) {
int x = r.nextInt(101);
System.out.println(x);
}
}
}
public class Example2 {
public static void main(String[] args){
HW2 ex= new HW2();
}
}
```
3. 呈現程式碼HelloEvent.java及執行截圖。
```java=
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class HelloEvent implements ActionListener {
JFrame f;
JButton b;
HelloEvent(){
f = new JFrame("HelloEvent");
f.setLayout(new FlowLayout());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container c = f.getContentPane();
b = new JButton("HelloEvent");
b.addActionListener(this);
c.add(b);
f.setSize(600,400);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e){
JOptionPane.showMessageDialog(f,"HelloEvent");
}
public static void main(String[] args){
new HelloEvent();
}
}
```

4. [Swing]建立兩個JFrame物件(f1,f2),各放入一個JButton物件(b1,b2),一個顯示"Hello",另一個顯示"World",設定這兩個JButton的事件處理(ActionEvent),並顯示f1。當按下b1後隱藏f1顯示f2,當按下b2後隱藏f2顯示f1。呈現程式碼及執行截圖。
```java=
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class HelloJFrame implements ActionListener {
JFrame f1,f2;
JButton b1,b2;
HelloJFrame(){
f1 = new JFrame("Frame1");
f1.setLayout(new FlowLayout());
f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container c1 = f1.getContentPane();
b1 = new JButton("Hello");
b1.addActionListener(this);
c1.add(b1);
f1.setSize(600,400);
f1.setVisible(true);
f2 = new JFrame("Frame2");
f2.setLayout(new FlowLayout());
f2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container c2 = f2.getContentPane();
b2 = new JButton("World");
b2.addActionListener(this);
c2.add(b2);
f2.setSize(600,400);
f2.setVisible(false);
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==b1){
f2.setVisible(true);
f1.setVisible(false);
} else{
f1.setVisible(true);
f2.setVisible(false);
}
} // end of if-else
public static void main(String[] args){
new HelloJFrame();
}
}
```

