增強for循環(huán)
?int []s={10,20,30,40,50}; ? ? ? ? //常規(guī) ? ? ? ? ?for (int i = 0; i < 5; i ) { ? ? ? ? ? ? ?System.out.println(s[i]); ? ? ? ? } ? ? ? ? ?System.out.println("========================================="); ? ? ? ? ?//增強for ? ? ? ? ?for(int j:s) { ? ? ? ? ? ? ?System.out.println(j); ? ? ? ? }
![image-20210120123851469]()
增強就是簡化語句
練習
打印三角形
?for (int i = 0; i <= 5; i ) { ? ? ? ? ? ? ?for (int i1 = 5; i1 >=i; i1--) { ? ? ? ? ? ? ? ? ?System.out.print(" "); ? ? ? ? ? ? } ? ? ? ? ? ? ?for (int i2 = 1; i2 <= i; i2 ) { ? ? ? ? ? ? ? ? ?System.out.print("*"); ? ? ? ? ? ? } ? ? ? ? ? ? ?for (int i3 = 1; i3 < i; i3 ) { ? ? ? ? ? ? ? ? ?System.out.print("*"); ? ? ? ? ? ? } ? ? ? ? ? ? ?System.out.println(); ? ? ? ? }
![image-20210120132239800]()
方法
?public static void main(String[] args) { ? ? ? ? ?int sum=add(1,2); ? //1 2 為實參 ? ? ? ? ?System.out.println(sum); ? ? ? ? } ? public static int add (int a,int b){ //a、b為形參(形式參數(shù)) ? ? ? ? ?return a b; ? //有返回的方法必須有return、且是方法結(jié)束的標志 ? ? ? ? } ?public static double add (double a,double b){ ? ? ? ? ?return a b; ? ? ? ? } //方法重載 ?//============================================== ?public static void main(String[] args) { ? ? ? ? ?add(1,2,5,99,44); ?? ? ? ? ? } ? ? ? ? ?public static void add (int... b)//可變參數(shù) ? ? ? ? { ? ? ? ? ?for(int i=0;i<b.length;i ){ ? ? ? ? ? ? ?System.out.println(b[i]); ? ? ? ? } ? ? ? ? }
方法的重載要求
-
方法名稱必須相同
-
參數(shù)列表必須不同
-
返回類型可以相同也可以不同
-
僅僅是類型不同不足以構(gòu)成重載
可變參數(shù)
-
一個方法中只能指定一個可變參數(shù)
-
他必須是方法的最后一個參數(shù),前面可以有普通參數(shù)
計算器
?public static void main(String[] args) { ? ? ? ? ?pro(); ? ? } ? ? ?public static void pro(){ ? ? ? ? ?System.out.println("請輸入二元計算式:"); ? ? ? ? ?Scanner s=new Scanner(System.in); ? ? ? ? ?double f = s.nextDouble(); ? ? ? ? ?String str = s.next(); ? ? ? ? ?double g = s.nextDouble(); ? ? ? ? ?switch (str) { ? ? ? ? ? ? ?case "*": ? ? ? ? ? ? ? ? ?System.out.println(che(f, g)); ? ? ? ? ? ? ? ? ?pro(); ? ? ? ? ? ? ? ? ?break; ? ? ? ? ? ? ?case "/": ? ? ? ? ? ? ? ? ?System.out.println(chu(f, g)); ? ? ? ? ? ? ? ? ?pro(); ? ? ? ? ? ? ? ? ?break; ? ? ? ? ? ? ?case " ": ? ? ? ? ? ? ? ? ?System.out.println(add(f, g)); ? ? ? ? ? ? ? ? ?pro(); ? ? ? ? ? ? ? ? ?break; ? ? ? ? ? ? ?case "-": ? ? ? ? ? ? ? ? ?System.out.println(min(f, g)); ? ? ? ? ? ? ? ? ?pro(); ? ? ? ? ? ? ? ? ?break; ? ? ? ? ? ? ?default: ? ? ? ? ? ? ? ? ?System.out.println("輸入有誤,請重新輸入"); ? ? ? ? ? ? ? ? ?pro(); ? ? ? ? ? ? ? ? ?break; ? ? ? ? } ? ? ? ? ?s.close(); ? ? ? ? } ? ? ?public static double add(double a,double b){ ? ? ? ? ?return a b; ? ? } ? ? ?public static double min(double a,double b){ ? ? ? ? ?return a-b; ? ? } ? ? ?public static double che(double a,double b){ ? ? ? ? ?return a*b; ? ? } ? ? ?public static double chu(double a,double b){ ? ? ? ? ?return a/b; ? ? }
?
來源:https://www./content-4-832651.html
|