12月29日 面向對象02(工具類&代碼塊)

靜態的應用——工具類(構造方法私有化,僅提供功能)


製作說明書: 
1.寫一個工具類
2.添加文檔註釋
3.用工具解析文檔註釋 javadoc工具
4.格式:javadoc -d 目錄(.表示當前目錄) -author -version 類.java


/**
說明……
@author 作者
@version 版本
*/


/**
說明……
@param 參數名稱 參數解釋
@param 參數名稱 參數解釋
@return 返回值說明
*/




對數組進行操作(需求:1.遍歷數組 2.獲取最大值 3.獲取最小值 4.查找索引)
/**
*這是一個工具類,對數組進行操作
*@author Vincent
*@version 1.0
*/
public class ArrayTool
{
private ArrayTool(){}
/**
*對數組進行遍歷,遍歷格式爲:【元素1,元素2,元素3,元素4……】
*@param arr 要遍歷的數組
*/
public static void ArrayPrint(int[] arr)
{
System.out.print("[");
for(int x = 0 ; x < arr.length ;x++)
{
if(x == arr.length-1)
{
System.out.println(arr[x]+"]");
}
else
{
System.out.println(arr[x]+",");
}
}
}
/**
*輸出數組中的最大值
*@param arr 輸入要操作的數組
*@return 返回數組中的最大值
*/
public static int ArrayMax(int[] arr)
{
int max = arr[0];
for(int x = 0 ; x < arr.length ; x++)
{
if(max < arr[x])
{
max = max+arr[x];
arr[x] = max-arr[x];
max = max-arr[x];
}
}
return max;
}
/**
*輸出數組中的最小值
*@param arr  輸入要操作的數組
*@return 返回數組中的最小值
*/
public static int ArrayMin(int[] arr)
{
int min = arr[0];
for(int x = 0 ; x < arr.length ; x++)
{
if(min > arr[x])
{
min = min+arr[x];
arr[x] = min-arr[x];
min = min-arr[x];
}
}
return min;
}
/**
*獲取指定元素的第一次出現時的索引,如果不存在,則輸出-1
*@param arr 輸入要操作的數組
*@param num 要查找的數字
*@return 返回數字的索引,如果數字不存在,則返回-1
*/
public static int ArrayFindIndex(int[] arr,int num)
{
for(int x = 0 ; x < arr.length ; x++)
{
if(num == arr[x])
{
return num;
}
}
return -1;
}
}




猜數字的小遊戲:
(需求:系統隨機生成一個從1-100的數據,用戶進行猜,並輸出"大了",“小了”,“you win”一


共有十次猜測機會)
/*(需求:系統隨機生成一個從1-100的數據,用戶進行猜,並輸出"大了",“小了”,“you win”
一共有十次猜測機會)*/
import java.util.Scanner;
public class GuessNumber
{
public static void main(String[] args)
{
//初始化猜測次數
int count = 10;
int myNum = 0;
Scanner sc = new Scanner(System.in);
//生成一個隨機數
int num = (int)(Math.random()*100)+1;
while(count > 0)
{
System.out.println("請輸入一個數字,您還有"+count+"次機會");
myNum = sc.nextInt();
if(myNum > num)
{
System.out.println("大了。。。");
count--;
}
else if(myNum < num)
{
System.out.println("小了。。。");
count--;
}
else
{
count = 0;
}
}
if(count == 0)
{
if(myNum == num)
{
System.out.println("YOU WIN");
}
else
{
System.out.println("YOU LOSE");
}
}
}
}




代碼塊:在Java中,使用{}括起來的代碼被稱爲代碼塊。
根據其位置和聲明的不同,可以分爲


局部代碼塊:局部位置,用於限定變量的生命週期。


構造代碼塊:在類中的成員位置,用{}括起來的代碼,每次調用構造方法執行前,都會先執行構造代碼


塊。
對對象進行初始化


靜態代碼塊:在類中的成員位置,用{}括起來的代碼,只不過它用static修飾了
對類初始化。


//對代碼塊的使用:


class Code
{
static{
int a = 1000;
System.out.println("類已經被創建"+a);
}
{
int b = 100;
System.out.println("對象被創建"+b);
}
public Code()
{
System.out.println("構造函數已經執行");
}
public Code(int a)
{
System.out.println("構造函數"+a+"已經被執行");
}
}


public class Demo
{
public static void main(String[] args)
{
{
int a = 10;
System.out.println(a);
}
//System.out.println(a);
Code c = new Code();
Code c1 = new Code(1);
}
}




運行順序: 靜態代碼塊 > 構造代碼塊 > 構造函數



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章