java程序----for循環

1.水仙花數的輸出與計數
/*
 * 1.輸出所有的水仙花數
 * 2.統計水仙花數的個數
 * 水仙花數=個位^3+十位^3+百位^3
 * */
public class shuixianhua {
	public static void main(String[] args){
    //定義初始個數爲0
		int count=0;
		//利用for循環輸出
		for(int x=100;x<1000;x++){
			//求個位,十位,百位的表示
			int ge=x%10;
			int shi=x/10%10;
			int bai=x/10/10%10;
			if(x==(ge*ge*ge+shi*shi*shi+bai*bai*bai)){
				 count++; 
				 System.out.println("水仙花數是:"+x);
			}
			  
			}
		System.out.println("水仙花數的個數是:"+count+"個");
	}

}

輸出結果:
水仙花數是:153
水仙花數是:370
水仙花數是:371
水仙花數是:407
水仙花數的個數是:4個


2.乘法表的輸出

//鍵盤錄入一個數據,求出對應的乘法表,使用方法
import java.util.Scanner;
public class chengfabiao {
public static void main(String[] args) {
	Scanner sc=new Scanner(System.in);
	System.out.println("請輸入行數:");
	int a=sc.nextInt();
	print(a);
	
}
public static void print(int m){
	for(int x=1;x<=m;x++){
		for(int y=1;y<=x;y++){
			System.out.print(y+"*"+x+"="+(y*x)+"\t");
		}
		System.out.println();
	}
}
請輸入行數:
5

1*1=1	
1*2=2	2*2=4	
1*3=3	2*3=6	3*3=9	
1*4=4	2*4=8	3*4=12	4*4=16	
1*5=5	2*5=10	3*5=15	4*5=20	5*5=25	

3.金字塔星星的輸出

import java.util.Scanner;//導包
//鍵盤錄入行數和列數,輸出金字塔星星,方法調用,for函數的嵌套public class xing2 {public static void main(String[] args) {


       //創建鍵盤錄入對象
	Scanner sc=new Scanner(System.in);
      //輸入並且接收對象
	System.out.println("請輸入行數:");
	int a=sc.nextInt();
	printxing(a);
}
public static void printxing(int a){
	   for(int x=1;x<=a;x++){
		for(int k=1;k<=a-x;k++){
			System.out.print(" ");
		}
		for(int y=1;y<=(x-1)*2+1;y++){
		  System.out.print("*");	 
		}
		
		System.out.println();
	}
	   for(int x=a;x>=0;x--){
			for(int k=1;k<=a-x;k++){
				System.out.print(" ");
			}
			for(int y=1;y<=(x-1)*2+1;y++){
			  System.out.print("*");	 
			}
			
			System.out.println();
		}
    }
}
a=5時,輸出結果如下:
    *
   ***
  *****
 *******
*********
*********
 *******
  *****
   ***
    *
4.一維數組的遍歷和逆序

//逆序一個數組
public class nixu {
public static void main(String[] args) {
	int[] arr={12,325,346,36,47};
	System.out.println("逆序前:");
	print(arr);
	System.out.println("逆序後:");
	inprint(arr);
	print(arr);
}
public static void print(int[] arr){
	System.out.print("[");
	for(int a=0;a<arr.length;a++){
		if(a==arr.length-1){
			System.out.print(arr[a]+"]");
		}else{
			System.out.print(arr[a]+",");
		}
	}System.out.println();
}
  
public static void inprint(int[] arr){
	for(int x=0,y=arr.length-1;x<y;x++,y--){
		 int temp=arr[x];
		 arr[x]=arr[y];
		 arr[y]=temp;
	}
}

}
逆序前:
[12,325,346,36,47]
逆序後:
[47,36,346,325,12]








發佈了29 篇原創文章 · 獲贊 10 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章