? 發問時間： 電腦與網際網路程式設計 · 1 0 年前

# java之物件導向相關問題

class BarkDog

{

int length, weight, age;

public BarkDog (){}

public BarkDog (int len, int wei, int a)

{

length = len;

weight = wei;

age = a;

}

public void bark()

{

String s;

int randomNum = (int) (Math.random()*2);

s=((randomNum == 1)?"WanWan, I am a dog":"Oooo..Wan!");

System.out.println(s);

}

public int returnIndex()

{

return length * weight / age;

}

}

### 1 個解答

• 阿逸
Lv 6
1 0 年前
最佳解答

以下次我構思的程式，你參考看看

import java.util.Scanner;

public class test{

public static void main(String args[]){

BarkDog dogA = new BarkDog(20 ,50 , 5);

BarkDog dogB = new BarkDog(23 ,32 ,3);

BarkDog dogC = new BarkDog(18 ,35 ,4);

int A = 0, B = 0, C = 0; //bark的紀錄放置這3個變數

System.out.println("***dog會bark 5次***");

System.out.println("***如果bark是\"WanWan, I am a dog\"請輸入[1]***");

System.out.println("***如果bark是\"Oooo..Wan!\"請輸入[2]***");

System.out.println();

Scanner sca = new Scanner(System.in);

int n = 5;// 這裡可以修改bark的次數

int z = 0;

System.out.println("首先是dogA");

for(int x = 1; x <= n; x++){

dogA.bark();

while(z !=1 || z !=2){

z = sca.nextInt();

if(z == 1 || z == 2)

break;

System.out.println("請輸入1或2 !!");

}

if(z == 1)

A++;

}

System.out.println("再來是dogB");

for(int x = 1; x <= n; x++){

dogB.bark();

while(z !=1 || z !=2){

z = sca.nextInt();

if(z == 1 || z == 2)

break;

System.out.println("請輸入1或2 !!");

}

if(z == 1)

B++;

}

System.out.println("再來是dogC");

for(int x = 1; x <= n; x++){

dogC.bark();

while(z !=1 || z !=2){

z = sca.nextInt();

if(z == 1 || z == 2)

break;

System.out.println("請輸入1或2 !!");

}

if(z == 1)

C++;

}

System.out.printf("dogA bark的length:%d, weight:%2d, age:%d,bark的次數為%3d\n"

, dogA.length, dogA.weight, dogA.age, A);

System.out.printf("dogB bark的length:%d, weight:%2d, age:%d,bark的次數為%3d\n"

, dogB.length, dogB.weight, dogB.age, B);

System.out.printf("dogC bark的length:%d, weight:%2d, age:%d,bark的次數為%3d\n"

, dogC.length, dogC.weight, dogC.age, C);

}

}

話說題目是[ "觀察"隨機亂數所產生的隨機現象 ]

結果還真的是得用觀察的才行呢...因為我沒注意到brak方法是void

結果我又只好中途重寫....(笑)

參考資料： 新手的我