Java Control Statements

Source: Internet
Author: User
Tags case statement ming

Introduction to Java Control statement experiment

In this experiment, we will learn about the grammatical knowledge of conditional control statements and circular control statements.

First, conditional control statements

We have a lot of choices in life and we make a series of judgments before we make a choice. For example, if we want to go out today, we will make a judgment on the weather. If the weather is good, we will go out, if the weather is bad, we will not go out. This need to judge the condition before the condition is fulfilled, we can use conditional control statements to achieve.

The IF statement is a judgment statement.

Grammar:

if(条件){    条件成立时执行的代码}

The If...else statement executes the code block of the If section when the condition is true, or to the Else section when the condition is not true. For example, if the one-month number of days is greater than 30 days, then Otsuki, or Yue.

Grammar:

if(条件){    代码块1}else{    代码块2}

The multiple if statement, in which condition 1 is not satisfied, will be judged by condition 2, and then the code in the Else block is eventually executed when none of the preceding conditions are true.

Grammar:

if(条件1){    代码块1}else if(条件2){ 代码块2}...else { 代码块n}

Note: If the IF (or else if, or else) condition is the only one that executes the statement, you can omit the curly braces! However, if there are multiple execution statements, then curly braces are indispensable.

Like what:

int days = 31;if(days > 30)    System.out.println("本月是大月");else System.out.println("本月是小月");

An If statement can be nested within the inner layer. Nested IF statements determine the condition of the inner if if the condition of the outer if is true.

Grammar:

if(条件1){    if(条件2){        代码块1 } else{ 代码块2 }}else{ 代码块3}

Next we do a simple exercise: Xiao Ming exam 78 points, 60 points above, 80 points for good, 90 points above for excellent, 60 points below to re-test, write a program, output Xiao Ming's situation bar.

The reference code is as follows:

PublicClassScorejudge {public static void main (string[] args) { int score = 78; if (score >= 60) {if (Score >= 80) {if (score >= 90) {System.out.println (  "excellent performance"); } else{System.out.println ( "good results");}} else{System.out.println ( "pass");}} else{System.out.println ( "need to retake");}}      

The wood above gives you a detailed description of the IF statement, and next we will learn another conditional statement: The switch statement. Using a switch statement is more concise when you need to make an equivalent judgment on an option. For example: The wave to 1 of the first prize, shake to 2 second prize, shake to 3 of the third prize, shake to the other no prize.

Grammar:

switch(表达式){    case 值1:        代码块1        break; case 值2: 代码块2 break; ... default: 默认执行的代码块}

When the value of a switch after the expression is the same as the value after the case statement, execution starts down from that position until the break statement is encountered or the switch statement block ends, and the code of the default block is executed if there is no matching case statement.

For example, the above example:

PublicClassDraw {public static void main (string[] args) {int num = 2; switch (num) {case  1: System.out.println ( "Congratulations, won the first prize"); break; case 2:system.out.println ( "Congratulations, Won the second Prize "); break; case 3:system.out.println ( "Congratulations, Won the third prize "); break; default:system.out.println ( "Sorry, come again next time")}}}     
Second, circular control statements

In our daily life, in order to accomplish certain things, we need to perform certain actions repeatedly, for example, when we walk, we have to repeat the left and right feet constantly. In the computer, for some repetitive things, is it necessary for us to constantly input it? There is actually a better way to loop the statement.

Let's take a look at the and in the Loop statement first while do...while .

whileGrammar:

while(条件){    代码块}

While the execution process is first judged, then executed.

    1. Determines whether the condition after the while is true or false

    2. When the condition is true, execute the code within the loop and repeat 1. 2. until the loop condition is not established.

do...whileGrammar:

do{    代码块}while(条件);

The execution of Do...while is performed first, in judgment (so the code within the loop executes at least once)

    1. Perform a loop operation first and then determine if the loop condition is true

    2. If the condition is true, continue execution 1. 2. until the loop condition is not established

The following example:

int i = 0;while(i < 100){    System.out.println("I love ShiYanlou!"); i++;}
int i = 0;do {    System.out.println("I love ShiYanlou!");    i++;} while(i < 100);

Now let's practice it: using while and do...while two methods to write a program that implements all the even numbers in 1-1000 and outputs them. Verify that the results of the two methods you output are the same?

Refer to the following:

PublicClasssumofodd {PublicStaticvoidMain(string[] args) {int i1 =1, I2 =1;int sum1 =0, sum2 = 0; while (i1 <= 1000) {//cycle 1000 Times Span class= "Hljs-keyword" >if (0 = = i1% 2) {//to determine whether it is even sum1 + = I1; //add even numbers to total} i1++; //i self-increment 1} System.out.println ( "while,1 to 1000, all even-numbered and as:" +SUM1); do {if (0 = = i2% 2" {//in the conditional statement, the value is written in front to prevent = = = Sum2 + = i2;} i2++;} while (i2 <= 1000); System.out.println ( "do...while,1 to 1000, all even-numbered and:" +sum2);}}      

Finally, let's learn another loop statement.for 语句

Grammar:

for(循环变量初始化; 循环条件; 循环变量变化){    循环操作}

For a more concise and readable structure than while and do...while statements, the order in which they are executed:

    1. Executes the loop variable initialization section, setting the initial state of the loop, which executes only once in the entire loop

    2. The loop condition is judged, the loop body code is executed if the condition is true, and if False, the loop is exited directly

    3. Execute loop variable change part, change the value of the loop variable, in order to make the next condition judgment

    4. Re-execute, in turn, 2. 3. 4. until the loop is exited

For example, calculate the sum of the numbers that cannot be divisible within 100:

    int sum = 0; // 保存不能被3整除的数之和    // 循环变量 i 初始值为 1 ,每执行一次对变量加 1,只要小于等于 100 就重复执行循环    for (int i = 1;i<=100;i++) { // 变量 i 与 3 进行求模(取余),如果不等于 0 ,则表示不能被 3 整除 if (i % 3 != 0) { sum = sum + i; // 累加求和 } } System.out.println("1到100之间不能被3整除的数之和为:" + sum);

Let's practice, using the for statement to implement the above practice topic.

The reference code is as follows:

 public  Class sumofodd {public static void main ( String[] args) {int sum = 0; for (int i = 1; I <= 1000; i++) {if (0 = = i% 2) {sum + = i;}} System.out.println ( "with for,1 to 1000, all even numbers are:" +sum);}}       

When speaking conditional control statements, to the students to explain the nested if statement, in the Loop statement, three kinds of circular statements can be nested themselves, can also be nested, the most common is the double cycle. In a double loop, the outer loop executes once, and the inner loop executes a circle.

For example, I want to print

*

**

***

****

Such a graphic

         // 外层循环控制行数        for (int i = 1; i<=4; i++ ) { // 内层循环控制每行的*号数 // 内层循环变量的最大值和外层循环变量的值相等 for (int j = 1; j<=i; j++ ) { System.out.print("*"); } // 每打印完一行后进行换行 System.out.println(); }

Practice: Print Such a graphic on the console

1

12

123

1234

12345

The reference code is as follows:

 public  Class printnum {public static void main ( String[] args) {//outer loop control number of rows for ( int i = 1; I<=5; i++) {// The inner loop controls the number of each row //the maximum value of the inner loop variable is equal to the value of the outer loop variable for (int j = 1; j<=i; J + +) {System.out.print (j);} //line-wrapping System.out.println () after each line is printed;} }} 
Three, jump statement

When we explained the switch statement above, we saw the break keyword, what's the use of it? Students, we will remove the code in the above switch exercises, break run a bit, found what problem? breakthe meaning of jumping out, often used in the condition and loop statements, to jump out of the Loop statement .

For example:

for(int i = 1; i <= 10; i++){    if(0 == i % 3){ break; } if(0 == i % 5){ System.out.println("我进来了!") }}

In the above code, the for statement will cause the code in the loop to loop 10 times, but when it i=3 enters the first conditional statement, it encounters break , ends the loop, and never gets into the second conditional statement.

In the jump statement, there is also a similar continue break , its role is to skip the loop in the body of the remaining statements to perform the next loop.

For example, we want to print all the odd numbers within 10:

for(int i = 1; i <= 10; i++){    if(0 == i % 2) //判断i是否为偶数 continue; //通过continue结束本次循环 System.out.println(i);}
Break is the end of the entire loop body, continue is the end of a single cycle

Say:

while (x + + < 10)
{
if (x = = 3)
{
Break
}
printf ("%d\r\n", X);
}
As a result, output 1 2 exits the entire while loop.

But if you use continue
while (x + + < 10)
{
if (x = = 3)
{
Continue
}
printf ("%d\r\n", X);
}
The result is: 1 2 4 5 6 7 8 9 See He's just not outputting 3 because he ended this cycle
Iv. operations

All the content of today is over, how do the students master it? We will take a programming question to test everyone.

A natural number greater than 1, except 1 and itself, can not be divisible by other natural numbers, in other words, the number except 1 and itself no longer have other factors of the number is called Prime, please program to determine whether 4549, 8461, 641, 313 is a prime number.

The reference code is as follows:

PublicClassJudgeprime {public static void main (string[] args) {int a = 4549; boolean result = true; for (int i=2; i*i < A; i++) {if (a% i = = 0) {//a in turn divided by the number of open after 2 to a (a can be divisible by 5, will be divisible (A/5)) result = FALSE; break;} } if (Result) {System.out.println (A+else System.out.println (A+" not prime number ")}}       

Java Control Statements

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.