Java Sample Collection (ii)

Source: Internet
Author: User
Tags case statement

Example 1. Swich statements

The expression in the switch statement must be an integer or character, and the constant value 1~ constant value n must also be an integer or character type. For the same switch statement, the constants of the case must differ from each other.

In a switch statement, the value of a constant expression after a case statement can be an integer, but must not be a real number, and a constant expression can be a character, but must not be a string.

1.1. The sample code is as follows:

ImportJava.util.Scanner; Public classGetswitch { Public Static voidMain (string[] args) {//TODO auto-generated Method StubScanner scan=NewScanner (system.in);//Create an input stream scannerSystem.out.println ("Today is the day of the week:"); intWeek=scan.nextint ();//defines the INT variable week, and assigns the input value to the receiving user        Switch(week) { Case1: System.out.println ("Today is Monday");//Output Information             Break;  Case2: System.out.println ("Today is Tuesday");  Break;  Case3: System.out.println ("Today is Wednesday");  Break; default: System.out.println ("Sorry,i don ' t know"); }            }}

1.2. Each case keyword in a switch statement can be a conditional branch, but for multiple conditions that deal with the same business, you can associate the cases branch together,

Omit the break statement between them, and implement the business process in the last same case branch and execute the break statement. The sample code is as follows:

 Public classExample { Public Static voidMain (String args[]) {//Main MethodScanner scan=NewScanner (system.in);//Create an input stream scannerSystem.out.println ("Please enter the employee's name:");//prompt to enter informationString Empname=scan.nextline ();//Receive input informationSYSTEM.OUT.PRINTLN ("The programming language in which the clerk is engaged:");//prompt to enter informationString Language=scan.nextline ();//Receiving user Information        Switch(Language.hashcode ()) {//determining staff task scope according to programming language         Case3254818://hash code for Java         Case2269730://hash code for Java         Case2301506://hash code for JavaSystem.out.println ("Clerk:" +empname+ "in Java development work");  Break;  Case2112://hash code for C #         Case3104://hash code for C #System.out.println ("Clerk:" +empname+ "in C # development work");  Break;  Case-709190099://hash code for ASP.         Case9745901://hash code for ASP.         Case955463181://hash code for ASP.System.out.println ("Clerk:" +empname+ "Working in ASP"));  Break; default: System.out.println ("Clerk:" +empname+ "not engaged in development work"); }    }}

Example 2. Verifying the legality of login information

Most system login modules will accept login information entered by the user via the keyboard, which will be verified by the login module. This example simply implements the authentication of the login information by if...else The conditional judgment of the statement. The code is as follows:

ImportJava.util.Scanner; Public classChecklogin { Public Static voidMain (string[] args) {Scanner scan=NewScanner (system.in);//Create an input stream scannerSystem.out.println ("Please enter user name:");//prompt to enter user name informationString User=scan.nextline ();//Receive user inputSystem.out.println ("Please enter user password:");//Prompt to enter password informationString Pwd=scan.nextline ();//Receive user input        if(!user.equals ("Tiger")) {//judging the legality of the userSystem.out.println ("The user name you entered is incorrect"); }Else if(!pwd.equals ("soft123")) {//determine the legality of login passwordSYSTEM.OUT.PRINTLN ("The login password you entered is incorrect"); }Else{System.out.println ("Login Successful"); }    }}

Example 3. Traversal statements

The 3.1. Foreach statement is a specially simplified version of the For statement, and the foreach statement does not completely replace the for statement, but any foreach statement can be rewritten as a For Statement loop version.

The FOR statement traversal syntax format is: for (element variable x: Traverse object obj) {The Java statement that references X;}. The sample code is as follows:

 Public class repetition{    publicstaticvoid  main (String args[]) {        int arr[]={12,33,8,14};                // declaring a one-dimensional array        System.out.println ("Elements in a one-dimensional array are:");    // Output Information         for (int x:arr) {                               //foreach statement            System.out.println (x + "\ T")        ;     }}}

3.2. Using the While loop to iterate through the array, the sample code is as follows:

 Public classErgodicarray { Public Static voidMain (string[] args) {String aves[]= {"Tiger", "Lion", "elephant", "Leopard", "fox", "Oriole", "Parrot", "Lark"};//defining a string array and assigning values        intintarr=0;//defining index variables and assigning initial valuesSystem.out.println ("The Zoo has:");  while(intarr<aves.length) {//iterating through an array using the Whild loopSystem.out.print (aves[intarr++] + "");//self-increment index value        }    }}

Example 4. Jump statement

4.1. Break Jump statement: In a switch statement, the break statement is used to abort the following case statement, and the break statement can also be applied to forcibly exit the loop in the for, while, and do...while loops.

This is the restriction that ignores any other statements and loop conditions in the loop body. The sample code is as follows:

 Public classBreakdemo { Public Static voidMain (String args[]) {string Flag= "The sum of natural numbers from 1 to 100 is:";//defining a String variable flag and assigning an initial value        intsum=0;//defines the int variable sum and assigns an initial value of 0         for(inti=1;i<=100;i++) {sum+=i;//add each number to add            if(sum>2000) {//if and greater thanFlag= "from 1 to" +i+ "is the number of consecutive integers:";  Break;//Exit Loop}} System.out.println (Flag+sum); }}

The result of the execution is: the number of consecutive integers from 1 to 63 is: 2016

The 4.2. Continue statement can only be applied in the for, while, and Do...while loop statements, allowing the program to skip the statement immediately following it for the next loop. The sample code is as follows:

 public  class   Continuedemo { public  static  void   main (string[] args) {S            Tring Flag  = "The odd number from 1 to 10 is:"; //  Defines the output string variable flag and initializes the value          SYSTEM.OUT.PRINTLN (flag);  for  (int  I=1;i<10;i++ if  (I%2==0 continue  ;        } System.out.print (i  + "" 

Like:

 Public classcontinuedemo{ Public Static voidMain (String args[]) {inti=0;//define the loop incrementSystem.out.println ("All even numbers within 10 are:"));  while(i<10) {i++;//the accumulated I value            if(i% 2 ==1) {//when the value of I is divided by 2 1 o'clock, it means that the number is not even                Continue;//make the Next loop} System.out.println (i+ " ");//value of Output I        }    }}

Example 5. Terminating the Loop body

Loops are used in complex business processes to improve the performance and readability of the program, but there are special cases in the loop, such as the need to interrupt the loop immediately to execute the following business logic for some reason. The sample code is as follows:

 Public classbreakcycle { Public Static voidMain (string[] args) {//TODO auto-generated Method StubSystem.out.println ("\ n ************************ sample ************************* for the middle of a single cycle"); String aves[]= {"Tiger", "Lion", "elephant", "Leopard", "fox", "Oriole", "Parrot", "Lark"};//defining a string array and assigning valuesSystem.out.println ("Tell me what animals you have before you find the first elephant.") ");  for(String str:aves) {//foreach traversal array            if(Str.equals ("Elephant")) {//If you encounter an elephant                 Break;//Interrupt Loop} System.out.println ("There:" +str+ "");//Otherwise, the output array element} System.out.println ("\n\n********************* interrupt double-layer Loop example *************************"); int[] mynum= {{68,79,56,83},                {23,77,80,89},                {92,95,99,46}};//creating an array of integersSYSTEM.OUT.PRINTLN ("Data in this array: \ n first\t second\t Third\tfourth"); No1: for(int[] is:mynum) {//traversing a data table             for(intI:is) {System.out.println (i+ "\ T");//Output Data                if(i<60) {//Interrupt all output immediately if you encounter data that is less than 60 in the middleSystem.out.println ("\ n So and on," +i+ "");  BreakNo1;        }} System.out.println (); }    }}

The result of the execution is:


Example of a mid-segment single cycle *************************
Before you find the first elephant, tell me what animals are there.
There are: Tigers
There: Lions


Example of interrupting a double-layer loop *************************
The data in the array:
First Second Thirdfourth
68
79
56

So and on,56

Java Sample Collection (ii)

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.