国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
Control statements can make our program logical/organized, and we can use control statements to implement a "business ".
Selection statements mainly include two types: if and switch!
 switch語句
循環(huán)語句while、do...while、for
?for循環(huán)
while循環(huán)
do...while循環(huán)
轉(zhuǎn)向語句:break、continue
break語句
continue語句
3.小試牛刀
Home Java javaTutorial Detailed examples of Java basic control statements

Detailed examples of Java basic control statements

Jun 10, 2022 pm 03:27 PM
java

This article brings you relevant knowledge about java, which mainly introduces related issues about control statements, including selection statements, loop statements, redirect statements and other related content. The following is Let's take a look, hope it helps everyone.

Detailed examples of Java basic control statements

## Recommended study: "

java video tutorial"

1. Classification

How to receive user keyboard input

##java.util.Scanner s = new java.util.Scanner(System.in); Receive integer: int i = s.nextInt() Receive string: String str = s.next();

Or divide the first sentence into two steps:

import java.util.Scanner;

## Scanner s = new Scanner(System.in)

Control statement classification

Control statements can make our program logical/organized, and we can use control statements to implement a "business ".

Control statements include 3 categories:

Selection statement, loop statement, turn statement

Selection statement (branch statement): if statement, switch statement; Loop statement: for loop , while loop, do..while.. loop; Steering statement: break, continue, return (discussed later);


2. Detailed explanation of statements

Select statement if , switch

Selection statements mainly include two types: if and switch!

if statement

if statement is a branch statement , can also be called a conditional statement. The syntax format of the if statement:

The first way of writing:

??if(布爾表達(dá)式){
????????????????????java語句;
????????????????????java語句;
????????????????}
A brace {} here is called a branch. The execution principle of this syntax is: if the result of the Boolean expression is true, the program in the curly brackets will be executed, otherwise the code in the curly brackets will not be executed.


The second way of writing:

?if(布爾表達(dá)式){??//?分支1
????????????????????java語句;?????
????????????????}else{??//?分支2
????????????????????java語句;
????????????????}
Execution principle: If the result of the Boolean expression is true, branch 1 will be executed, and branch 2 will not implement. If the result of the Boolean expression is false, branch 1 is not executed and branch 2 is executed.

## The third way of writing:
??if(布爾表達(dá)式1){?//?分支1
????????????????????java語句;
????????????????}else?if(布爾表達(dá)式2){?//?分支2
????????????????????java語句;
????????????????}else?if(布爾表達(dá)式3){?//?分支3
????????????????????java語句;
????????????????}else?if(布爾表達(dá)式4){?//?分支4...
????????????????????java語句;
????????????????}....

Execution principle: first judge "Boolean expression 1", if "Boolean expression 1" is true, then branch 1 is executed, and then the if statement ends. When the result of "Boolean expression 1" is false, then the result of Boolean expression 2 will continue to be judged. If the result of Boolean expression 2 is true, branch 2 will be executed, and then the entire if will end. Judge from top to bottom, mainly depending on which branch the first true occurs. The branch corresponding to the first true is executed. As long as one branch is executed, the entire if ends.



The fourth way of writing:
? ?
??if(布爾表達(dá)式1){?//?分支1
????????????????????java語句;
????????????????}else?if(布爾表達(dá)式2){?//?分支2
????????????????????java語句;
????????????????}else?if(布爾表達(dá)式3){//?分支3
????????????????????java語句;
????????????????}else?if(布爾表達(dá)式4){//?分支4
????????????????????java語句;
????????????????}else{
????????????????????java語句;?//?以上條件沒有一個成立的。這個else就執(zhí)行了。
????????????????}

Notes

The conditions for the if statement can only be Boolean expressions, true and false!

It cannot be specific numbers or variables, which is strictly distinguished from the C language;
For if statements, there can only be one branch executed under any circumstances, and there cannot be two or more. Branch execution. As long as one branch in the if statement is executed, the entire if statement ends. (For a complete if statement);

Among the above four syntax mechanisms, any one with an else branch can guarantee that one branch will be executed. Among the above four types, the first and third types do not have else branches. Such statements may cause the last branch to not be executed. The second and fourth types will definitely have one branch executed; When there is only one "java statement;" in the branch, then the curly brackets {} can be omitted, but for the sake of readability, it is best not to omit it. Control statements can be nested
between control statements, but when nesting, it is best to analyze them one by one, rather than analyzing them together.


Example analysis

Example 1

For the variable itself is a Boolean type, our method There are many; because the type itself is Boolean, as long as it is grammatical and logical! For example: sex, sex == true, or written as a ternary operator!

public?class?Test01{
	public?static?void?main(String[]?args){
//1.本身就是布爾類型
		boolean?sex??=?true;
		if(sex){//sex?==?true也可以
			System.out.println('男');
		}
		else{
			System.out.println('女');
		}
//2.也可以用三目運算符
		char?str?=?sex?'男':'女';
		System.out.println(str);
//3.一種特殊情況
		if(sex?=?true){//賦值運算符,也可以編譯通過,永遠(yuǎn)只執(zhí)行if語句
			System.out.println('男');
		}
		else{
			System.out.println('女');
		}

	}
}

例2

對于變量是整型,我們的方式就很少了,因為if后面跟的必須是布爾表達(dá)式;所以要寫成一個表達(dá)式,讓它生成一個布爾類型,例如:i == 100;

如果if...else后面只跟著一條語句,大括號可以省略;如果省略寫了兩個java語句也是沒問題的;但是就會和下面的else斷開,造成else沒有if語句,編譯報錯;

//1.本身不是布爾類型
		int?i?=?100;
		if(i?==?100){
			System.out.println(true);
		}
		else{
			System.out.println(false);
		}
//2.else缺少if
		if(sex)
			System.out.println('男');
			System.out.println("Hello?wprld");//合乎語法的
		else?//這一行報錯,因為else缺少if
			System.out.println('女');
????//上面等價于
????????if(sex){
			System.out.println('男');
???????????}
			System.out.println("Hello?wprld");
		else?
			System.out.println('女');

例3

public?class?Test02{
	public?static?void?main(String[]?args){
		//從鍵盤接收數(shù)據(jù)
		System.out.print("請輸入你的年齡:");
		java.util.Scanner?s?=?new?java.util.Scanner(System.in);
		int?age?=?s.nextInt();
//1.方法1
		if(age<0 || age >150){
			System.out.println("年齡不合法");
		}else?if(age?<=?5){
			System.out.println("嬰幼兒");
		}else?if(age?<=?10){
			System.out.println("少兒");
		}else?if(age?<=?18){
			System.out.println("少年");
		}else?if(age?<=?35){
			System.out.println("青年");
		}else?if(age?<=?55){
			System.out.println("中年");
		}else{
			System.out.println("老年");
		}

//2.方法2代碼改良
		String?str?=?"老年";
		if(age<0 || age >150){
			System.out.println("年齡不合法");
			return;//不合理就跳出循環(huán),防止后面在打印
		}else?if(age?<= 5){
			str = "嬰幼兒";
		}else if(age <= 10){
			str = "少兒";
		}else if(age <= 18){
			str = "少年";
		}else if(age <= 35){
			str = "青年";
		}else if(age <= 55){
			str = "中年";
		}
		System.out.println(str);//最后公用一個打??;因為每次只能打印一個
	}
}

例4
系統(tǒng)接收一個學(xué)生的考試成績,根據(jù)考試成績輸出成績的等級。

等級:優(yōu):[90~100]、良:[80~90) 、中:[70-80)、及格:[60~70)、不及格:[0-60)

要求成績是一個合法的數(shù)字,成績必須在[0-100]之間,成績可能帶有小數(shù)。

public class Test03{
	public static void main(String[] args){
		java.util.Scanner s = new java.util.Scanner(System.in);
		System.out.print("請輸入你的成績:");
		double grade = s.nextDouble();
		String str = "優(yōu)";

		if(grade <0 || grade >100){
			System.out.println("分?jǐn)?shù)不合法");
			return;?//不合理就跳出循環(huán),防止后面在打印
		}else?if(grade<60){
			str = "不及格";
		}else if(grade < 70){
			str = "及格";
		}else if(grade < 80){
			str = "中";
		}else if(grade < 90){
			str = "良";
		}
		System.out.println(str);//最后公用一個打?。灰驗槊看沃荒艽蛴∫粋€
	}
}

例5

從鍵盤上接收天氣的信息:1表示:雨天
0表示:晴天
同時從鍵盤上接收性別的信息:1表示:男
0表示:女
業(yè)務(wù)要求:
當(dāng)天氣是雨天的時候:男的:打一把大黑傘
女的:打一把小花傘
當(dāng)天氣是晴天的時候:男的:直接走起,出去玩耍
女的:擦點防曬霜,出去玩耍

public class Test04{
	public static void main(String[] args){
		java.util.Scanner s = new java.util.Scanner(System.in);
		System.out.print("請輸入天氣,1表示雨天,0表示晴天:");
		int weather = s.nextInt();
		System.out.print("請輸入性別,1表示男,0表示女:");
		int sex = s.nextInt();

		if(weather == 1){
			if(sex == 1){
				System.out.println("打一把大黑傘");
			}else{
				System.out.println("打一把小花傘");
			}
		
		}else{
			if(sex == 1){
				System.out.println("直接走起,出去玩耍");
			}else{
				System.out.println("擦點防曬霜,出去玩耍");
			}
		}
	}
}

switch語句

switch語句也是選擇語句,也可以叫做分支語句。
switch語句的語法格式:

 switch(值){
            case 值1:
                java語句;
                java語句;...
                break;
            case 值2:
                java語句;
                java語句;...
                break;
            case 值3:
                java語句;
                java語句;...
                break;
            default:
                java語句;
            }

其中:break語句不是必須的;default分支也不是必須的。
switch語句支持的值有:支持int類型以及String類型
一定要注意JDK的版本,JDK8之前不支持String類型,只支持int。在JDK8之后,switch語句開始支持字符串String類型。
switch語句本質(zhì)上是只支持int和String,但是byte,short,char也可以
使用在switch語句當(dāng)中,因為byte short char可以進(jìn)行自動類型轉(zhuǎn)換。

switch語句的執(zhí)行原理
拿“值”與“值1”進(jìn)行比較,如果相同,則執(zhí)行該分支中的java語句,然后遇到"break;"語句,switch語句就結(jié)束了。
如果“值”與“值1”不相等,會繼續(xù)拿“值”與“值2”進(jìn)行比較,如果相同,則執(zhí)行該分支中的java語句,然后遇到break;語句,switch結(jié)束。
注意:如果分支執(zhí)行了,但是分支最后沒有“break;”,此時會發(fā)生case 穿透現(xiàn)象。所有的case都沒有匹配成功,那么最后default分支會執(zhí)行。

實例分析

例1

寫一個完整的switch語句;接收鍵盤輸入,根據(jù)輸入的數(shù)字來判斷星期幾。
0 星期日、1 星期一....、假設(shè)輸入的數(shù)字就是正確的。0到6

public class Test05{
	public static void main(String[] args){
		java.util.Scanner s = new java.util.Scanner(System.in);
		System.out.print("請輸入[0-6]的天數(shù):");
		int day = s.nextInt();
		switch(day){
		case 0:
			System.out.println("星期日");
			break;
		case 1:
			System.out.println("星期一");
			break;
		case 2:
			System.out.println("星期二");
			break;
		case 3:
			System.out.println("星期三");
			break;
		case 4:
			System.out.println("星期四");
			break;
		case 5:
			System.out.println("星期五");
			break;
		case 6:
			System.out.println("星期六");
			break;
		default:
			System.out.println("選擇錯誤");
			break;
		}
		
	}
}

例2
系統(tǒng)接收一個學(xué)生的考試成績,根據(jù)考試成績輸出成績的等級。必須用switch來寫

等級:優(yōu):[90~100]、良:[80~90) 、中:[70-80)、及格:[60~70)、不及格:[0-60)

要求成績是一個合法的數(shù)字,成績必須在[0-100]之間,成績可能帶有小數(shù)。

public class SwitchTest02{
	public static void main(String[] args){
		//提示用戶輸入學(xué)生成績
		java.util.Scanner s = new java.util.Scanner(System.in);
		System.out.print("請輸入學(xué)生成績:");
		double score = s.nextDouble();
		//System.out.println(score);
		if(score < 0 || score >?100){
			System.out.println("您輸入的學(xué)生成績不合法,再見!");
			return;?
		}

		//?程序能夠執(zhí)行到這里說明成績一定是合法的。
		//?grade的值可能是:0?1?2?3?4?5?6?7?8?9?10
		//?0?1?2?3?4?5?不及格
		//?6?及格
		//?7?中
		//?8?良
		//?9?10?優(yōu)
		
		int?grade?=?(int)(score?/?10);?//?95.5/10結(jié)果9.55,強(qiáng)轉(zhuǎn)為int結(jié)果是9
		String?str?=?"不及格";
		switch(grade){
		case?10:?case?9:
			str?=?"優(yōu)";
			break;
		case?8:?
			str?=?"良";
			break;
		case?7:
			str?=?"中";
			break;
		case?6:
			str?=?"及格";
		}
		System.out.println("該學(xué)生的成績等級為:"?+?str);
	}
}

循環(huán)語句while、do...while、for

?for循環(huán)

for循環(huán)的語法機(jī)制以及運行原理


? ? ? ? 語法機(jī)制:? ?

?for(初始化表達(dá)式;?條件表達(dá)式;?更新表達(dá)式){
????????????????循環(huán)體;?//?循環(huán)體由java語句構(gòu)成
????????????????java語句;
????????????????java語句;
????????????????java語句;
????????????????java語句;
????????????????....
????????????}

? ? ? 注意:
?? ??? ??? ??? ?第一:初始化表達(dá)式最先執(zhí)行,并且在整個循環(huán)中只執(zhí)行一次。
?? ??? ??? ??? ?第二:條件表達(dá)式結(jié)果必須是一個布爾類型,也就是:true或false
? ? ? 執(zhí)行原理:
? ? ? ? ? ?(1)先執(zhí)行初始化表達(dá)式,并且初始化表達(dá)式只執(zhí)行1次。
???????????(2)然后判斷條件表達(dá)式的結(jié)果,如果條件表達(dá)式結(jié)果為true,則執(zhí)行循環(huán)體。
???????????(3)循環(huán)體結(jié)束之后,執(zhí)行更新表達(dá)式。
???????????(4)更新完之后,再判斷條件表達(dá)式的結(jié)果,如果還是true,繼續(xù)執(zhí)行循環(huán)體。
???????????(5)直到更新表達(dá)式執(zhí)行結(jié)束之后,再次判斷條件時,條件為false,for循環(huán)終止。? ? ? ?更新表達(dá)式的作用是:控制循環(huán)的次數(shù),換句話說,更新表達(dá)式會更新某個變量的值,這樣條件表達(dá)式的結(jié)果才有可能從true變成false,從而?終止for循環(huán)的執(zhí)行,如果缺失更新表達(dá)式,很有可能會導(dǎo)致死循環(huán)。

?例1

public?class?ForTest02{
	public?static?void?main(String[]?args){
//1.?最簡練的for循環(huán)
??????//初始化表達(dá)式、條件表達(dá)式、更新表達(dá)式?其實都不是必須的!??!
		for(;;){
			System.out.println("死循環(huán)");
		}

//2.最常見的for循環(huán)
		for(int?i?=?0;i?< 10;i++){
			System.out.println("i = " + i); // 0 1 2 3....9
		} 
		System.out.println(i);//錯誤: 找不到符號,i的范圍只在for循環(huán)內(nèi)

//3.i變量的作用域就擴(kuò)大了。
		int i = 0;
		for(;i < 10;i++){
			System.out.println("i -->?"?+?i);?//?0?1?2?3....9
		}
		System.out.println("i?=?"?+?i);?//10,這里的i就可以訪問了

//4.變形
		for(int?k?=?1;?k?<= 10; ){
			System.out.println("k -->?"?+?k);?
			k++;//?1?2?3?4?5?6?7?8?9?10?
		}
//5.變形
		for(int?k?=?1;?k?<= 10; ){
			k++;
			System.out.println("value -->?"?+?k);?//?2?3?4?5?6?7?8?9?10?11
		}

	}
}

例2

public?class?ForTest03{
	public?static?void?main(String[]?args){
//1.?for的其它形式
		for(int?i?=?10;?i?>?0;?i--){
			System.out.println("i?=?"?+?i);?//?10?9?8?7?6?5?4?3?2?1
		}
//2.?變形
		for(int?i?=?0;?i?< 10; i += 2){
			System.out.println("value1 = " + i); // 0 2 4 6 8 
		}

//3. 死循環(huán)	
		for(int i = 100; i >?0;?i?%=?3){
			System.out.println("value2?=?"?+?i);?//?100?1?1...?1
		}

	}
}

例3:求1-100所得奇數(shù)和

public?class?Test07{
	public?static?void?main(String[]?args){
		int?i?=?0;
		int?sum?=?0;
		for(i=1;i<=100;i+=2){
			sum+=i;
		}
		System.out.println("sum = "+sum);//2500
	}
}

例4:嵌套循環(huán)

public class Test08{
	public static void main(String[] args){
//1.注意初始化放里面
	for(int i =0;i< 2;i++){
		for(int j=0;j<10;j++){
		   System.out.print(j+" ");
	   }
		System.out.println();
	}//打印兩行0-9的數(shù)字
//2.初始化放外面
    int n = 0;
	for(int m = 0;m<2;m++){
		for(;n<10;n++){
			System.out.print(n+" ");
		}
		System.out.println();
	}//打印一行0-9的數(shù)字
 }
	
}

例5:九九乘法表

public class Test09{
	public static void main(String[] args){
		for(int i=1;i<=9;i++){
			for(int j=1;j<=i;j++){
				System.out.print(j+"*"+i + "=" +i*j+"  ");
			}
			System.out.println();
		}
	}
}

while循環(huán)

while循環(huán)的語法機(jī)制以及執(zhí)行原理
語法機(jī)制:

 while(布爾表達(dá)式){
                    循環(huán)體;
                }

執(zhí)行原理:
判斷布爾表達(dá)式的結(jié)果,如果為true就執(zhí)行循環(huán)體,循環(huán)體結(jié)束之后,再次判斷布爾表達(dá)式的結(jié)果,如果還是true,繼續(xù)執(zhí)行循環(huán)體,直到布爾表達(dá)式結(jié)果為false,while循環(huán)結(jié)束。

while循環(huán)有沒有可能循環(huán)次數(shù)為0次?
可能;while循環(huán)的循環(huán)次數(shù)是:0~n次。

例1

public class WhileTest01{
	public static void main(String[] args){
//1.死循環(huán)
		while(true){
			System.out.println("死循環(huán)");
		}
//2.本質(zhì)上while循環(huán)和for循環(huán)原理是相同的。
		for(初始化表達(dá)式; 布爾表達(dá)式; 更新表達(dá)式){
				循環(huán)體;
			}

		初始化表達(dá)式;
		while(布爾表達(dá)式){
				循環(huán)體;
				更新表達(dá)式;
			}
//3.例子對比
		//----for	
        for(int i = 0; i < 10; i++){
			System.out.println("i --->"?+?i);
		?}
????????//----while
		int?i?=?0;
		while(i?< 10){
			System.out.println("i = " + i);
			i++;
		}


//4.for和while完全可以互換,只不過就是語法格式不一樣。
		for(int i = 0; i < 10; ){
			i++;
			System.out.println("i --->"?+?i);?//?1?2?3?..?9?10
		}

		int?i?=?0;
		while(i?< 10){
			i++;
			System.out.println("i = " + i); // 1 2 3 .. 9 10
		}


	}
}

do...while循環(huán)

do..while循環(huán)語句的執(zhí)行原理以及語法機(jī)制:
語法機(jī)制:

        do {
                循環(huán)體;
            }while(布爾表達(dá)式);

注意:do..while循環(huán)最后的時候別漏掉“分號”;

執(zhí)行原理:
先執(zhí)行循環(huán)體當(dāng)中的代碼,執(zhí)行一次循環(huán)體之后,判斷布爾表達(dá)式的結(jié)果,如果為true,則繼續(xù)執(zhí)行循環(huán)體,如果為false循環(huán)結(jié)束。
對于do..while循環(huán)來說,循環(huán)體至少執(zhí)行1次。循環(huán)體的執(zhí)行次數(shù)是:1~n次。
對于while循環(huán)來說,循環(huán)體執(zhí)行次數(shù)是:0~n次。

例1

public class Test10{
	public static void main(String[] args){
		int i = 0;
//1.
		do{
			//第一種方法
			System.out.println(i);
			i++;
			//第二種方法
			System.out.println(i++);
		}while(i<10);//0...9
//2.
		i = 0;
		do{		
			System.out.println(++i);
		}while(i<10);//1...10
		
	}
}

轉(zhuǎn)向語句:break、continue

break語句

break;語句比較特殊,特殊在:break語句是一個單詞成為一個完整的java語句。
break的作用:終止當(dāng)前循環(huán),直接跳出循環(huán);

break主要用在兩個地方,其它位置不行:
第一個位置:switch語句當(dāng)中,用來終止switch語句的執(zhí)行。用在switch語句當(dāng)中,防止case穿透現(xiàn)象,用來終止switch。
第二個位置:break;語句用在循環(huán)語句當(dāng)中,用在for當(dāng)中、用在while當(dāng)中、用在do....while當(dāng)中;用來終止循環(huán)的執(zhí)行。

break;語句的執(zhí)行并不會讓整個方法結(jié)束,break;語句主要是用來終止離它最近的那個循環(huán)語句。

怎么用break;語句終止指定的循環(huán)呢?
第一步:你需要給循環(huán)起一個名字,例如:

       a: for(){
                    b:for(){
                    
                    }
                }

第二步:終止:break a;

例1

public class BreakTest01{
	public static void main(String[] args){
		for(int i = 0; i < 10; i++){
			if(i == 5){
//1.break;語句會讓離它最近的循環(huán)終止結(jié)束掉。終止的不是if,不是針對if的,而是針對離它最近的循環(huán)。
				break; 
			}
			System.out.println("i = " + i); // 0 1 2 3 4
		}

//2.這里的代碼照常執(zhí)行。break;的執(zhí)行并不會影響這里。
		System.out.println("Hello World!");

//3.常用的終止內(nèi)存的for
		for(int k = 0; k < 2; k++){ // 外層for
			for(int i = 0; i < 10; i++){ // 內(nèi)層for
				if(i == 5){
					break; //這個break;語句只能終止離它最近的for,內(nèi)層的for
				}
				System.out.println("i ===>?"?+?i);?
			}
		}

		System.out.println("------------------------------------------");

//4.終止外層的for,起一個別名!
		a:for(int?k?=?0;?k?< 2; k++){ 
			b:for(int i = 0; i < 10; i++){
				if(i == 5){
					break a; //終止指定的循環(huán)。
				}
				System.out.println("i ===>?"?+?i);?
			}
		}

		System.out.println("呵呵");

	}
}

continue語句

continue翻譯為:繼續(xù);continue語句和break語句要對比著學(xué)習(xí);

continue語句的作用是:終止當(dāng)前"本次"循環(huán),直接進(jìn)入下一次循環(huán)繼續(xù)執(zhí)行。
continue語句后面也可以指定循環(huán);

?a:for(;;更新表達(dá)式1){
????????????????b:for(;;更新表達(dá)式2){
????????????????????if(){
????????????????????????continue?a;
????????????????????}
????????????????????code1;
????????????????????code2;
????????????????????code3;
????????????????}
????????????}

例1

public?class?ContinueTest01{
	public?static?void?main(String[]?args){
//1.對于break直接跳出當(dāng)前循環(huán)
		for(int?i?=?0;?i?< 10; i++){
			if(i == 5){
				break;
			}
			System.out.println("i = " + i);//0、1、2、3、4
		}

		System.out.println("----------------------------");

//2.對于continue是跳出當(dāng)前的一次循環(huán),繼續(xù)下一次循環(huán)
		for(int i = 0; i < 10; i++){
			if(i == 5){
				continue;
			}
			System.out.println("i = " + i); //輸出結(jié)果是0-9沒有5
		}

	}
}

3.小試牛刀

例1:計算1000以內(nèi)所有不能被7整除的整數(shù)之和

public class Test01{
	public static void main(String[] args){
		int sum = 0;
		for(int i = 1;i<=1000;i++){
			if(i%7 != 0){
				sum +=i;
			}
		}
	System.out.println("sum="+sum);
	}
}

例2:計算 1+2-3+4-5+6-7....+100的結(jié)果

注意除1以外,偶數(shù)是正,奇數(shù)是負(fù);所以我們就從2開始循環(huán),把sum初始化為1就可

//方法1:
public class Test02{
	public static void main(String[] args){
		int sum = 1;
		for(int i=2;i<=100;i++){
			if(i%2 ==0){
				sum+=i;
			}
			else{
				sum-=i;
			}
		}
	System.out.println(sum);
	}
}
//方法2:定義一個flag標(biāo)記,用來控制正負(fù),一個數(shù)一個數(shù)進(jìn)行處理
public class Test02{
	public static void main(String[] args){
		int sum = 1;
		int flag = 1;
		for(int i=2;i<=100;i++){
			sum +=flag*i;
			flag = -flag;
		}
	System.out.println(sum);
	}
}

例3:從控制臺輸入一個正整數(shù),計算該數(shù)的階乘。

public class Test03{
	public static void main(String[] args){
		java.util.Scanner s = new java.util.Scanner(System.in);
		System.out.print("請輸入一個整數(shù):");
		int num = s.nextInt();
		int ret = 1;
		//方法1
		for(int i=1;i<=num;i++){
			ret*=i;
		}
		//方法2
		for(int i = num;i>0;i--){
			ret*=i;
		}
	System.out.println(ret);
	}
}

例4:判斷一個數(shù)是不是質(zhì)數(shù)

//方法1:
public?class?Test04{
	public?static?void?main(String[]?args){
		java.util.Scanner?s?=?new?java.util.Scanner(System.in);
		int?num?=?s.nextInt();
		int?i?=?0;
		for(i?=?2;i<num;i++){
			if(num%i == 0){
			 System.out.println(num+"不是質(zhì)數(shù)");
			 break;
			}
		}
		if(i == num){
			System.out.println(num+"是質(zhì)數(shù)");
	}
}
//方法2:
public class Test04{
	public static void main(String[] args){
		java.util.Scanner s = new java.util.Scanner(System.in);
		int num = s.nextInt();
		int i = 0;
		boolean str = true;//也相當(dāng)于一個標(biāo)記
		for(i = 2;i<num;i++){
			if(num%i == 0){
			 str = false;//不是更改標(biāo)記
			 break;
			}
		}
		System.out.println(num+(str ? "是":"不是")+"質(zhì)數(shù)");//根據(jù)標(biāo)記輸出值
	}
}

例5:打印金字塔

    *
   ***
  *****
 *******
*********
public class Test05{
	public static void main(String[] args){
		java.util.Scanner s = new java.util.Scanner(System.in);
		int n = s.nextInt();
		for(int i=0;i<n;i++){
			for(int j=0;j<n-i-1;j++){
					System.out.print(" ");
			}
			for(int j=0;j<2*i+1;j++){
				System.out.print("*");
			}
		System.out.println();
		}
		
	}
}

例6:

小芳的媽媽每天給她2.5元錢,她都會存起來,但是,每當(dāng)這一天是存錢的第5天
或者5的倍數(shù)的話,她都會花去6元錢,請問,經(jīng)過多少天,小芳才可以存到100元錢!

public class Test06{
	public static void main(String[] args){
		double money = 0;
		int day = 0;
		while(true){//這也可以寫成while(money<100),這樣就不需要break了
			money += 2.5;
			day++;
			if(day%5 == 0){
				money -= 6;
			}
			if(money >=?100){
				break;
			}
		}
	System.out.println("需要"+day+"天存到"+money+"元錢");
	}
}

例7:

一個數(shù)如果恰好等于它的因子之和,這個數(shù)就是完數(shù),例如 6 = 1 + 2 + 3,編程
找出1000內(nèi)所有的完數(shù)。

public?class?Test07{
	public?static?void?main(String[]?args){
		for(int?i=2;i<=1000;i++){//1不算完數(shù),從2開始
//注意sum的位置,寫在內(nèi)循環(huán),因為每次都要重置sum為0
			int sum = 0;
//i取一半,最好的是取根號i,目前還沒學(xué)習(xí)庫函數(shù),先取i/2
			for(int j=1;j<= i/2;j++){
				if(i%j == 0){
					sum += j;
				}
			}
			if(sum == i){
				System.out.println(i);
			}
		}
		
	}
}

例8:求一個數(shù)是幾位數(shù),并逆序打印每一位

public class Test08{
	public static void main(String[] args){
		java.util.Scanner s = new java.util.Scanner(System.in);
		int num = s.nextInt();
		int count = 0;
		int tmp = num;
		//求位數(shù)
		while(tmp != 0){
				count++;
				tmp /= 10;
		}
		System.out.println("位數(shù)是"+count+"位");
		//逆序打印
		tmp = num;
		while(tmp != 0){
			System.out.println(tmp%10);
			tmp /= 10;
		}
	}
}

例9

1 10 100 1000 
2 20 200 2000 
3 30 300 3000 
4 40 400 4000
public class Test09{
	public static void main(String[] args){
		for(int i=1;i<=4;i++){
			int tmp = i;
			for(int j=1;j<=4;j++){
				System.out.print(tmp+" ");
				tmp *= 10;
			}
			System.out.println();
		}
	}
}

10

    *
   ***
  *****
 *******
*********
 *******
  *****
   ***
    *
public class Test10{
	public static void main(String[] args){
		java.util.Scanner s = new java.util.Scanner(System.in);
		int num = s.nextInt();
		x(num);
	}
	public static void x(int n){
//1.打印上半部分
		for(int i=0;i<n;i++){
			for(int j=0;j<n-i-1;j++){
				System.out.print(" ");
			}
			for(int j=0;j<2*i+1;j++){
				System.out.print("*");
			}
			System.out.println();
		}
//2.打印下半部分
		for(int i=0;i<n-1;i++){
			for(int j=0;j<=i;j++){
				System.out.print(" ");
			}
			for(int j=0;j<2*(n-i-1)-1;j++){
				System.out.print("*");
			}
			System.out.println();
		}
	}
}

11

籃球從 5 米高的地方掉下來,每次彈起的高度是原來的 30%,經(jīng)過幾次彈起,籃球的高度是 0.1 米。

public class Test11{
	public static void main(String[] args){
		int count = 0;
		double h = 5;
		while(h >=?0.1){
			h?*=?0.3;
			count++;
	????}	
	?System.out.println(count);
	}
}

推薦學(xué)習(xí):《java視頻教程

The above is the detailed content of Detailed examples of Java basic control statements. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1488
72
VSCode settings.json location VSCode settings.json location Aug 01, 2025 am 06:12 AM

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

How to handle transactions in Java with JDBC? How to handle transactions in Java with JDBC? Aug 02, 2025 pm 12:29 PM

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

python itertools combinations example python itertools combinations example Jul 31, 2025 am 09:53 AM

itertools.combinations is used to generate all non-repetitive combinations (order irrelevant) that selects a specified number of elements from the iterable object. Its usage includes: 1. Select 2 element combinations from the list, such as ('A','B'), ('A','C'), etc., to avoid repeated order; 2. Take 3 character combinations of strings, such as "abc" and "abd", which are suitable for subsequence generation; 3. Find the combinations where the sum of two numbers is equal to the target value, such as 1 5=6, simplify the double loop logic; the difference between combinations and arrangement lies in whether the order is important, combinations regard AB and BA as the same, while permutations are regarded as different;

Mastering Dependency Injection in Java with Spring and Guice Mastering Dependency Injection in Java with Spring and Guice Aug 01, 2025 am 05:53 AM

DependencyInjection(DI)isadesignpatternwhereobjectsreceivedependenciesexternally,promotingloosecouplingandeasiertestingthroughconstructor,setter,orfieldinjection.2.SpringFrameworkusesannotationslike@Component,@Service,and@AutowiredwithJava-basedconfi

python pytest fixture example python pytest fixture example Jul 31, 2025 am 09:35 AM

fixture is a function used to provide preset environment or data for tests. 1. Use the @pytest.fixture decorator to define fixture; 2. Inject fixture in parameter form in the test function; 3. Execute setup before yield, and then teardown; 4. Control scope through scope parameters, such as function, module, etc.; 5. Place the shared fixture in conftest.py to achieve cross-file sharing, thereby improving the maintainability and reusability of tests.

Troubleshooting Common Java `OutOfMemoryError` Scenarios Troubleshooting Common Java `OutOfMemoryError` Scenarios Jul 31, 2025 am 09:07 AM

java.lang.OutOfMemoryError: Javaheapspace indicates insufficient heap memory, and needs to check the processing of large objects, memory leaks and heap settings, and locate and optimize the code through the heap dump analysis tool; 2. Metaspace errors are common in dynamic class generation or hot deployment due to excessive class metadata, and MaxMetaspaceSize should be restricted and class loading should be optimized; 3. Unabletocreatenewnativethread due to exhausting system thread resources, it is necessary to check the number of threads, use thread pools, and adjust the stack size; 4. GCoverheadlimitexceeded means that GC is frequent but has less recycling, and GC logs should be analyzed and optimized.

Advanced Spring Data JPA for Java Developers Advanced Spring Data JPA for Java Developers Jul 31, 2025 am 07:54 AM

The core of mastering Advanced SpringDataJPA is to select the appropriate data access method based on the scenario and ensure performance and maintainability. 1. In custom query, @Query supports JPQL and native SQL, which is suitable for complex association and aggregation operations. It is recommended to use DTO or interface projection to perform type-safe mapping to avoid maintenance problems caused by using Object[]. 2. The paging operation needs to be implemented in combination with Pageable, but beware of N 1 query problems. You can preload the associated data through JOINFETCH or use projection to reduce entity loading, thereby improving performance. 3. For multi-condition dynamic queries, JpaSpecifica should be used

How to work with Calendar in Java? How to work with Calendar in Java? Aug 02, 2025 am 02:38 AM

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

See all articles