java中三種基本語句及四道例題
阿新 • • 發佈:2018-11-02
一、if-else語句
if (關係/邏輯/算術表示式) {
當條件成立時所要執行的函式功能
}
else {
當if後的條件不成立時所要執行的函式體
}
二、switch語句
switch(引數) {
case 表示式1(即有可能輸入的引數):
所要執行的函式體;
break;//用該語句跳出switch語句
case 表示式2:
所要執行的函式體;
break;
case 表示式3:
所要執行的函式體;
break;
default:
當輸入的引數在上述表示式不存在時要執行的函式體;
break;
}
三、for迴圈及四道利用for迴圈的例題
for(初始化,確定迴圈開始的位置;迴圈執行條件;迴圈變數在每次迴圈後如何變化){
在迴圈進行時要執行的函式體;
}//在此函式執行時在函式體執行結束後在進行迴圈變數的變化
1.求斐波那契數列前40項的和
public class TestDemo {
public static void fibSum(int n) {//定義一個斐波那契數列求和方法,引數n為要求多少項的和
int[] fib = new int[n];//定義一個一維陣列存放斐波那契數列
fib[0] = 1;
fib[1] = 1;//定義斐波那契數列前兩項,如不定義用通項公式會出現陣列越界問題
long sum = 0;//求和公式時使用
for (int i = 2;i < fib.length;i++) {//從第三項開始迴圈
fib[i] = fib[i-1] + fib[i-2];//斐波那契數列通項公式,將陣列中所有元素利用公式求出並儲存在陣列中
}
for (int i = 0;i < fib.length;i++) {//求和
sum = sum + fib[i];//將斐波那契數列每項相加求和
}
System.out.println( "斐波那契數列前"+ n +"項和為:" + sum);//輸出前n項的和
}
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
System.out.println("請輸入計算斐波那契數列前多少項的和:");
int n = scanner.nextInt();//由鍵盤輸入要求前多少項的和
fibSum(n);//呼叫斐波那契數列求和方法
}
}
2.用for迴圈產生20個隨機數(10-20)
public class TestDemo {
public static void randNum() {
System.out.println("10-20範圍內產生的20個隨機數:");
for(int i = 1;i <= 20;i++){//用迴圈控制輸出隨機數的個數
double random = Math.random()*(20-10)+10;//用求隨機數公式求10-20的隨機數
System.out.println(random);//輸出隨機數
}
}
public static void main(String[] args) {
randNum();//呼叫求隨機數的方法
}
}
3.輸入一個數字,求他是幾位數,並且順序輸出,逆序輸出
public class TestDemo {
public static void determine(String n) {
char[] number = n.toCharArray();//將字串型別的數字轉換成陣列儲存
System.out.println("該數為" + number.length + "位數" );
System.out.println("正序輸出該數:");
for (int i = 0;i < number.length;i++) {
System.out.print(number[i]);//將陣列中元素正序輸出,即將數字正序輸出
}
System.out.println();
System.out.println("逆序輸出該數:");
for (int i = number.length-1;i >= 0;i--) {
System.out.print(number[i]);//將陣列中元素逆序輸出,即將數字逆序輸出
}
}
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
System.out.println("請輸入一個正整數:");
String n = scanner.nextInt();//輸入數字,為字串型別,方便函式的編寫
determine(n);
}
}
4.求一個數字的二進位制數有幾個1
public class TestDemo {
public static int numof1(int n) {//2: 0000 0010
int count = 0;
while(n != 0) {
if((n &1) != 0) {
count++;
}
n = n >>> 1;
}
return count;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("請輸入要計算的數字:");
int n = scanner.nextInt();
numof1(n);
}
}