1.實現出入不定數量參數,進行排序(考點:可變參數其實是把參數存到數組里)
/**
* (double...d)表示可變參數,多少個參數都可以
* @author Administrator
*
*/
public class Max {
public static void main(String[]args){
double m=max(1.1,5.2,8.3,55.4,6.4,8.5);
System.out.println(m);
}
public static double max(double...d){
double largest=0;
for(double dl:d){
if(dl>largest){
largest=dl;
}
}
return largest;
}
}
2.抽獎
/**This program demonstrates array manipulation
* 實現抽獎
* 通過鍵盤輸入從多少個數抽取多少個數
* 將總數構建一個數組,為數組填滿元素,數組長度為輸入的總長度
* 建立抽取多少個數的數組,數組長度為輸入的想抽取的數,通過隨機數乘總數得到數字
* ,因為抽到的數字一定是總數里的數字,所以隨機數乘總數作為總數數組里的索引,
* 將索引值所得到的數填充到抽到的數字。
* 為控制每次索引得到的不是同一個數,把索引過的索引到的數字替換為總數數組里的最后一個數,
* 通過“索引位--”去除總數數組里的最后一個的索引位,
* 其實不是真實去除,只是永遠不會索引到,數組里還是存在的
*/
import java.util.*;
public class choujiang {
public static void main(String[] args){
Scanner in=new Scanner(System.in);
System.out.println("How many numbers do you want to draw?");
int a=in.nextInt();
System.out.println("What is the highest number you can draw");
int b=in.nextInt();
int []numbers=new int[a]; //往數組裝入總數字
for(int i=0;i<numbers.length;i++){
numbers[i]=i+1;
}
int []results=new int[b]; //往數組裝入要選多少個
for(int i=0;i<results.length;i++){
int r=numbers[(int) (Math.random()*a)]; //得出中獎號碼,讓隨機數不會出現去除數的索引
results[i]=numbers[r];
numbers[r]=numbers[a-1]; //將已經獲取到的數變一個值,在獲取此索引是獲取的不是相同值
a--;
}
Arrays.sort(results);
System.out.println(Arrays.toString(results));
}
}
3.數三進一問題
/**
* Test 數3退1的問題
* 建立一個500個孩子的布爾型數組,在里面為true,不再為false
* 一開始500孩子都在里面,賦值true
* 當剩下的孩子多于一個的時候進行循環
* 如果孩子在里面,數的數加1;當數等于3是,把孩子設置為false就不在里面了
* 退出如果語句,索引值增大,如果索引值等于數組長度,索引值歸零重新循環
* 多次循環后數組里只有一個值為true
* 通過for循環,if判斷true得出數組里的true值
* @author Administrator
*
*/
public class Count {
public static void main(String[]args){
Boolean [] a=new Boolean[500];
for(int i=0;i<a.length;i++){
a[i]=true;
}
int leftcount=500;
int count=0;
int temp=0;
while(leftcount>1){
if(a[temp]==true){
count++;
if(count==3){
a[temp]=false;
leftcount--;
count=0;
}
}
temp++;
if(temp==500){
temp=0;
}
}
for(int i=0;i<500;i++){
if(a[i]==true){
System.out.println(i);
}
}
}
}