Home > Java > javaTutorial > Detailed introduction to using conditional statements and loop structures in Java

Detailed introduction to using conditional statements and loop structures in Java

零下一度
Release: 2017-06-25 11:01:26
Original
2345 people have browsed it

Like any programming language, Java uses conditional statements and loop structures to determine the flow of control. This article will briefly explain conditions, loops and switches.

1. Block scope

Block (block) is a compound statement. It refers to several simple Java statements enclosed by a pair of curly brackets. Blocks determine the scope of variables.

For example:

 1 public class Code { 2 static 3 { 4     System.out.println("1"); 5 } 6 { 7     System.out.println("2"); 8 } 9 public Code()10 {11     System.err.println("3");12 }13 public static void main(String[]args)14 {15     new Code();16 }17 }
Copy after login

Note: Variables with the same name cannot be declared in two nested blocks.

2. Conditional statement

Format 1:

if(condition)

{

statement1

statement2

.....

}

For example:

1 if(youSales>=target)2 {3    performance="Satisfactory";4    bonus=1000;5 }
Copy after login

Format 2 :

if (condition) statement1 else statement2

For example:

 1 if(youSales>=target) 2 { 3   performance=“Satisfactory”; 4   bonus=100+10*(youSales-target“); 5  } 6 else 7 { 8   performance=”Unstatisfactory“; 9   bonus=0;10 }
Copy after login

3. Loop

When the condition is true, the while loop executes.

Format 1:

while(condition)statemnet

For example:

1 while (balance<goal)2 {3 balance+=payment;4 double interest=balance*interestRate/100;5 balance+=interest;6 years++;7 }
Copy after login

Format 2:

do statement while(condition);

 1 do 2     { 3         balance+=payment; 4         double interest=balance*interestRate/100; 5         balance+=interest; 6          7         year++; 8          9         System.out.printf("After year %d,your balance is %,.2f%,year,balance");10         11         System.out.print("Ready to retire?(Y/N)");12         input=in.next();13     }14     while(input.equals("N"));15 16     }
Copy after login

4. Determine the loop

The for loop statement is a general structure that supports iteration, using each A counter or similar variable updated after iterations to control the number of iterations.

The format is similar to the following:

for(int i=0; i

System.out.println(i);

4 examples:

 1 public class ShuZu1 { 2     public static void main(String[]args){ 3         int [][] x={{1,2,2,2,2},{3,3,3,3,3},{4,5,-1,17,55}}; 4         int result=qiuHe(x); 5         System.out.println("和是"+result); 6         } 7     public static int qiuHe(int[][]x){ 8         int s=0; 9         for(int i=0;i<x.length;i++)10         {11             for(int j=0;j<x[i].length;j++)12             {13                 s+=x[i][j];14                 }15             }16         return s;17     }18 }
Copy after login
 1 public class ShuZu2 { 2     public static void main(String[]args){ 3         int [][] x=new int[7][7]; 4         //生成随机数组,注意没有返回值,另外打印一行字 5         suiJi(x); 6         System.out.println("生成的数组是:"); 7          8         //显示数组内容,注意没有返回值 9         showArray(x);10         11         //取值12         float result=getAvg(x);13         System.out.println("平均数是"+result);14         15     }16     static float getAvg(int [][] x){17         float s=0;18         for(int i=0;i<x.length;i++){19             for(int j=0;j<x[i].length;j++){20                 s+=x[i][j];21             }22         }23         return s/(x.length*x[0].length);24     }25     static void suiJi (int[][]x){           //这里我出错了。返回值写了int型,不应该的。思考一下。26         for(int i=0;i<x.length;i++){27             for(int j=0;j<x[i].length;j++){28             x[i][j]=(int)(Math.random()*10);29             }30         }31     }32     static void showArray(int[][]x){        //这里我出错了。返回值写了int型,不应该的。思考一下。33         for(int i=0;i<x.length;i++){34             for(int j=0;j<x[i].length;j++){35                 System.out.print(x[i][j]+"\t");// 给数据空格36             }37             System.out.println();//打印换行38         }39     }40 }
Copy after login
 1 import java.util.Arrays; 2 public class SuZu3{ 3     public static void main(String[] args) { 4         int [] x={2,-1,7,777,6,764,85896,65554,0,874785,417825,74};    
 5         sort(x,&#39;n&#39;); 6         for(int i=0;i<x.length;i++){ 7             System.out.print(x[i]+"\t"); 8             } 9         }10     //给数组进行选择性排序11     //调用API进行升序12     static void sort(int[]x,char Flag){13         if(&#39;A&#39;==Flag){14             Arrays.sort(x);15             }16         else {17             for(int i=0;i<x.length-1;i++){18                 for(int j=0;j<x.length-1-i;j++){19                     int temp=0;20                     if(x[j]<x[j+1]){21                         temp=x[j];22                         x[j]=x[j+1];23                         x[j+1]=temp;24                         }25                     }26                 }27             }28         }29     }
Copy after login
 1 import java.util.Scanner; 2  3 public class Suzu4 { 4     public static void main(String[] args) { 5         System.out.println("请输入");//这个命令只能紧贴在Scanner scan = new Scanner(System.in);的上面或下面才有效。 6         Scanner scan = new Scanner(System.in); 7         //System.out.println("请输入");或者放在Scanner scan = new Scanner(System.in);的下面 8         String str = scan.nextLine();// nextLine才是接收一行 9         10         char[] s = str.toCharArray();// 把字符串转换称一个字符数组11         scan.close();12         int letterCount = 0;13         int numberCount = 0;14         int spaceCount = 0;15         int otherCount = 0;16         for (int i = 0; i < s.length; i++) {17             if (s[i] >= 'a' && s[i] <= &#39;z&#39; || s[i] >= 'A' && s[i] <= &#39;Z&#39;) {18                 letterCount++;19             } else if (s[i] >= '1' && s[i] <= '9') {20                 numberCount++;21             } else if (s[i] == ' ') {22                 spaceCount++;23             } else {24                 otherCount++;25             }26         }27         System.out.println("字母有" + letterCount + "个");28         System.out.println("数字有" + numberCount + "个");29         System.out.println("空格有" + spaceCount + "个");30         System.out.println("其他有" + otherCount + "个");31     }32 }//ctrl+shift+f 是代码格式化33 //ctrl+shift+o  是导包
Copy after login

5. Multiple selection: switch statement

The format is similar to the following:

switch(choice)

case 1:

.....

break;

case 2:

......

break;

......

//You can have a few more cases (end them with break)

default:

....

break;

Note:

case tag can be:

* Type is char, byte, short or a constant expression of int.

* Enum constants

* Starting from Java SE 7, case labels can also be string literals.

The above is the detailed content of Detailed introduction to using conditional statements and loop structures in Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template