java類和對象練習題1


1.請定義一個交通工具(Vehicle)的類,其中有:
⦁ 屬性:速度(speed),體積(size)等
⦁ 方法:移動(move()),設置速度(setSpeed(int speed)),設置體積(setSize(int size))加速speedUp(),減速speedDown()等
在測試類Vehicle中的main()中實例化一個交通工具對象,通過方法給它初始化speed,size的值,並打印出來。另外,調用加速,減速的方法對速度進行改變。

 

code:

public class Vehicle {
 double speed;    //速度屬性
 double size;     //體積屬性
 
 public Vehicle(){   //構造方法
  speed=1.0;
  size=1.0;
 }
 public void move(){
                      //移動
 }
 public void setSpeed(int speed){
  this.speed=speed;     //設置速度
 }
 public void setSize(int size){
  this.size=size;
 }                           //設置體積
 public void speedUp(){
  speed=speed*2;          //加速方法
 }
 public void speedDown(){
  speed=speed-1;         //減速方法
 }
}

 

 


public class TestVehicle {
 public static void main(String[] args) {
 Vehicle v;           //聲明對象;
 v=new Vehicle();     //為對象分配變量
 
 System.out.println("初速度為:"+v.speed);
 v.speedUp();
 System.out.println("加速后速度為:"+v.speed);
 v.speedDown();
 System.out.println("減速后速度為:"+v.speed);
 }
}
 
 
 
 
 
 
 
2.
 

關鍵詞:題目加分析

內容(A)

定義一個復數類,在主函數中實現復數的相加運算

#include<iostream.h>

#include<math.h>

class  F{

int a,b;

public:

void set(int t1,int t2) {a=t1;b=t2;}

void print()

{

char op={b>=0? '+':'-'}; //根據虛部b的值決定其正負號

cout<<a<<op<<abs(b)<<"i"<<endl; //字符“i”為復數的虛部標記

}

int geta() {return a;}

int getb() {return b;}

};

void main()

{

F f1,f2,f3;

f1.set(1,2); //A

f1.print(); //B

f2.set(3,-4); //C

f2.print(); //D

int a1,b1;

a1=f1.geta()+f2.geta(); //E

b1=f1.getb()+f2.getb(); //F

f3.set(a1,b1); //G

f3.print(); //H

}

(B)程序中類F的所有成員函數均定義為公有函數,所以在類體外,如A~H行均可以通過對象直接調用這些函數。類F的數據成員a和b的訪問特性是私有的,所以不能在類體外直接使用。

 
3.
 

關鍵詞:題目一個

內容:找出一個整形數組中的元素的最大值

用類與對象的方法做:

#include<iostream.h>

using namespace std;

class Array_max{

private:   //聲明在類的外部不可訪問的隱私成員

int array[10];

int max;

public:  //聲明在類的外部可以訪問的開發的成員函數

void set_value(){

int i;

cout<<"請輸出10個整數"<<endl;

for(i=0;i<10;i++)

{

cin>>array[i];

}

};

void max_value(){

int i;

max=array[0];

for(i=1;i<10;i++){

if(array[i]>max)

max=array[i];

}

};

void show_value(){

cout<<"max is:"<<max<<endl;

};

};

int main()

{

Array_max array1;

array1.set_value(); //初始化操作

array1.max_value(); //求最大值的操作

array1.show_value(); //輸出最大的數

return 0;

}

 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM