Java基本流程控制语句
生活随笔
收集整理的這篇文章主要介紹了
Java基本流程控制语句
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
package com.org.lxh;import java.util.Scanner;/*** Java流程控制語句,if,if……else,switch,while,do……while,for等等* @author hemmingway <hemmingway@163.com>***/
public class CommCtrl {/*** @param args*/public static void main(String[] args) {// TODO Auto-generated method stub//1.輸入一個年份,判斷是不是閏年Scanner scan = new Scanner(System.in);System.out.println("輸入一個年份:");long year;try{year = scan.nextLong(); //當輸入非數字的時候判斷異常if(year%4 == 0 && year%100 != 0 || year%400 == 0)System.out.println(year + "是閏年");elseSystem.out.println(year + "不是閏年");}catch(Exception e){e.printStackTrace();}//2.黃蓉難倒瑛姑的數學題System.out.println("今有物不知其數,三三數之剩二,五五數之剩三,七七數之剩二,問幾何?");for(int j = 1; j < 1000; j++){if(j%3 == 2 && j%5 == 3 && j%7 == 2){System.out.print(j + " ");}}System.out.println("");//3.李白提壺買酒的問題。//李白街上走,提壺去買酒,遇店加一倍,見花喝一斗,五遇店和花,喝光壺中酒。問壺中原先有多少酒?System.out.println("李白街上走,提壺去買酒,遇店加一倍,見花喝一斗,五遇店和花,喝光壺中酒。問壺中原先有多少酒?");double x = 0.0f; //壺中酒,單位為斗for(int i = 5; i>0; i--){x = x + 1;x = x/2;}System.out.println("壺中原先有酒" + x + "斗");//另外一種方法分析//第一次遇見店和花,2x-1//第二次 2(2x-1)-1=4x-3//第三次,2(4x-3)-1=8x-7//第四次,2(8x-7)-1=16x-15//第五次,2(16x-15)-1=32x-31=0x = 31/32.0;System.out.println("壺中原先有酒31/32斗,即"+ x + "斗"); //4.輸出楊輝三角//數字表,兩則的數字都是1,其他位置的數字是正上方和左上方的數字之和,下面的代碼演示了用for循環打印出包含10行的楊輝三角System.out.println("打印包含10行的楊輝三角");int triangle[][] = new int[10][]; //可以修改行數for(int i = 0; i<triangle.length; i++){triangle[i] = new int[i+1];for(int j=0; j<i; j++){if(i ==0 || j==0 ||j==1){triangle[i][j]=1;}else{triangle[i][j] = triangle[i-1][j] + triangle[i-1][j-1];}System.out.print(triangle[i][j] + "\t");}//for(int j=0; j<=i; j++)System.out.println(); //換行}//for(int i = 0; i<triangle.length; i++)//5.while循環計算一個數列System.out.println("使用循環計算:1-1/2+1/3-1/4+1/5-1/6+1/7-1/8+……");int i =1;double num = 0.0;while(i<=10000){ //演示一個bug while(i<=100);{num = num + Math.pow(-1.0, i+1)*1.0/i;i++;}System.out.println("數列的結果趨向于" + num + ",即ln(2)=" + Math.log(2.0)); //Java中Math類的log函數默認是以e為底的,相當于數學的ln(2)函數//6.計算harmonic sum,即1+1/2+1/3+1/4+……System.out.println("計算harmonic sum,即1+1/2+1/3+1/4+……");int n = 1;double hn = 0.0;while(n<=1000){hn = hn + 1.0/n;n++;}System.out.println("harmonic sum 趨向于ln(N) :" + hn + ", ln(100)=" + Math.log(1000.0));}//end for main}//end for class
輸入一個年份:
2012
2012是閏年
今有物不知其數,三三數之剩二,五五數之剩三,七七數之剩二,問幾何?
23 128 233 338 443 548 653 758863 968
李白街上走,提壺去買酒,遇店加一倍,見花喝一斗,五遇店和花,喝光壺中酒。問壺中原先有多少酒?
壺中原先有酒0.96875斗
壺中原先有酒31/32斗,即0.96875斗
打印包含10行的楊輝三角
?
1?
1? 1?
1? 1? 1?
1? 1? 2? 1?
1? 1? 3? 3? 1?
1? 1? 4? 6? 4? 1?
1? 1? 5? 10 10 5? 1?
1? 1? 6? 15 20 15 6? 1?
1? 1? 7? 21 35 35 21 7? 1?
使用循環計算:1-1/2+1/3-1/4+1/5-1/6+1/7-1/8+……
數列的結果趨向于0.6930971830599583,即ln(2)=0.6931471805599453
計算harmonic sum,即1+1/2+1/3+1/4+……
harmonic sum 趨向于ln(N) :7.485470860550343,ln(100)=6.907755278982137
?
總結
以上是生活随笔為你收集整理的Java基本流程控制语句的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 到底能不能行了?微软收购动视暴雪又遭欧盟
- 下一篇: Java面向对象入门