Home  >  Article  >  Java  >  Java learning switch statement and loop statement

Java learning switch statement and loop statement

王林
王林forward
2019-12-16 12:01:022482browse

Java learning switch statement and loop statement

1. Switch statement

int a = 1,b =2;
switch(a+b){
	case 1:
	System.out.print(1);
	case 3:
	System.out.print(3);
	case 4:
    System.out.print(4);
    default:
    System.out.print(5);
}

1. First execute a b to get value 3

2. Find the corresponding case 3, and then continue down.

3. Execute all statements because there is no break

Online free video tutorial recommendation: java teaching video

Result:

345
int a = 2, b = 34;
switch(a + b){
	case 5:
	System.out.println(5);
	break;
    case 6:
    System.out.println(6);
    break;
    default:
    System.out.println(12);
}

1. Execute a b and get 36

2. Execute default

Result:

12

Judge the month

Scanner a = new Scanner(System.in);
System.out.print("please input a month:");
int month = a.nextInt();
switch(month){
	case 1: case 2: case 3:
	System.out.println("Spring");
	break;
	case 4: case 5: case 6:
	System.out.println("Summer");
	break;
	case 7: case 8: case 9:
	System.out.println("Autumn");
	break;
	case 10: case 11: case 12:
	System.out.println("Winter");
	break;
	default:
	System.out.println("fasle");
}
Scanner a = new Scanner(System.in);
System.out.print("please input a month:");
int month = a.nextInt();
switch(month){
	case 1: 
	case 2:
    case 3:
	System.out.println("Spring");
	break;
	case 4: 
	case 5: 
	case 6:
	System.out.println("Summer");
	break;
	case 7: 
	case 8: 
	case 9:
	System.out.println("Autumn");
	break;
	case 10: 
	case 11: 
	case 12:
	System.out.println("Winter");
	break;
	default:
	System.out.println("fasle");
}

Two The method is the same, but the multiple statements in the switch statement, that is, the statement block, do not need to be enclosed in curly braces, because the break statement will jump out, otherwise execution will continue.

2. Loop statement

Find the prime number within 1000

int j;
for (int i = 0; i < 1000; i++) {
	for (j = 2; j < i; j++) 
		if (i % j == 0)
			break;
    if (j == i)
    	System.out.println(i);
}

Result:

2
3
5
…

Of course, there is an obvious mistake in the above. The outer loop should be <=1000. Although it does not affect anything, it should be kept in mind.

for (int i = 0; i < 1000; i++) {
	if(i == 2)
		System.out.println(2);
    for (int j = 2; j < i; j++) {
    	if(i % j == 0)
        	break;
        if(j == i - 1 )
            System.out.println(i);
     }
}

Recommended related articles and tutorials: zero basic introduction to java

The above is the detailed content of Java learning switch statement and loop statement. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete