Java Learning (5), condition structure, and java learning condition Structure

Source: Internet
Author: User

Java Learning (5), condition structure, and java learning condition Structure

1. if... else statement

1 // use runtime 2 import java to import the package. util. optional; 3 public class IfDemo {4 public static void main (String [] args) {5 bytes input = new bytes (System. in); 6 System. out. println ("Enter the number of days off"); 7 int holiday = input. nextInt (); // obtain the integer input by the keyboard. next represents the string nextDouble represents the double type 8 if (holiday> 6) 9 {10 System. out. println ("go to Hainan"); 11} 12 else if (holiday> 3) 13 {14 System. out. println (""); 15} 16 else17 {18 System. out. println ("at home"); 19} 20} 21}View Code

Ii. switch

1 import java. util. callback; 2 public class SwitchDemo {3 public static void main (String [] args) 4 {5 callback input = new callback (System. in); 6 System. out. println ("enter a number from 1 to 5"); 7 int number = input. nextInt (); 8 switch (number) 9 {10 case 1: System. out. println ("1"); break; 11 case 2: System. out. println ("2"); break; 12 case 3: System. out. println ("3"); break; 13 case 4: System. out. println ("4"); break; 14 case 5: System. out. println ("5"); break; 15 default: System. out. println ("Error"); break; 16} 17} 18}View Code

Summary

1. constants after case cannot be repeated
2. The break can be omitted. Once omitted, the program continues to run until the break or switch ends.
3. The order of case can be reversed, and default can be placed at any position, usually at the end, which can be omitted
4. switc is used to match constants. The matching types include byte, short, int, char, String (jdk1.7 and above), and enum (jdk1.5)
5. Comparison between switch and multiple if... else statements
Switch is suitable for equivalent judgment, and is not suitable for range judgment. The syntax for equivalent judgment is more concise and intuitive.
Multi-if statement functions are more comprehensive than switch Functions

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.