Dark Horse Programmer--java Foundation--Selection, cycle

Source: Internet
Author: User

----------- Android Training , Java Training , Java Learning Technology blog, look forward to communicating with you! ------------

Today, we review the selection statements, looping statements, and arrays in Java Learning, and the choice statements in Java are almost as if, switch in the C language.
An If statement consists of a Boolean expression followed by one or more statements. The sequential structure of a program statement can only be executed once. If you want the same operation to execute multiple times, you need to use the loop structure.

There are three main loop structures in Java:

    • While loop
    • Do...while Cycle
    • For loop

  Usage of the For loop

First of all, say oh for loop, for loop is open boundary. Its general form is: for (< initialization >; < conditional expressions >; < increments >) statements; Initialization is always an assignment statement, which is used to assign an initial value to a loop control variable; A conditional expression is a relational expression that determines when to exit a loop; Increment defines how the loop control variable changes after each loop. Between these three sections with ";" Separate. For example: for (i=1; i<=10; i++) statements; In the above example, "I" is assigned an initial value of 1, to determine whether "I" is less than or equal to 10, if the execution of the statement, followed by an increase of 1. Then re-judge until the condition is false, i.e. i>10, the end loop.

For example, take a simple 99 multiplication table:

public class S99{public static void Main (string[] args) {//loop number of lines for (int i=1;i<=9;i++) {//Control column for (int j=1;j<=i;j++) { Algorithm System.out.print (i+ "*" +j+ "=" + (i*j) + "\ T");} System.out.print ("\ n");}}

  

 



Let's implement a For loop code that calculates student scores:
assumes a student's 5-course grade, which requires an output average


 1 package com.student.exam; 2/** 3 * Use for Loop 4 * Enter the student's 5 homework, query the student's total score and average scores 5 */6 import Java.util.Scanner;    7 8 public class Averagescores {9 public static void Main (string[] args) {ten int score;    Declare a variable, named score, to receive the student's performance value one by one int sum= 0;    Declare a variable named sum, which is used to store student scores and double avg = 0.0;    Declares a variable of type double, which is used to receive the calculated pupil's average of Scanner sc = new Scanner (system.in);    Get keyboard input System.out.println ("Please enter student's name:"); String name = Sc.next ();        Assigns the obtained input to a string type name variable, i= 0; Declare a variable of type int, assign an initial value of 017 for (; i<5;i++) {//Loop 5 times Entry score of System.out.println ("Please enter 5 subjects of the" + (i+1) + "Door Score:"    ); score = Sc.nextint ();      Input results of sum + + + score; Equivalent to statement sum=sum+score; System.out.println (name+ "before" + (i+1) + "The results of the homework and is:" +sum); "System.out.println" Assembly    The performance is: "+sum"; avg = SUM/5; Calculated average score System.out.println (NAMe+ "The average score is:" +avg); 26 27}28 29} 

  


Because this is the basic part of Java, belongs to the initial Java, so each line of code gives a comment, for beginners more intuitive feeling, I put in the English identifier of the Chinese substitution.

Note: Although working in Eclipse works correctly in Chinese, it is recommended to use all English naming methods in real-world development.

Let's use the For loop in Java to output dot matrix graphics


 1 package com.student.exam;         2 3 public class Printtx {4 public static void main (string[] args) {5 PRINTJX (); 6 printpxsbx (); 7 PRINTSJX (); 8 9}10//print Rectangle one-by-one private static void Printjx () {i=1;i<=5;i++ for int. (int j=1;j<=5;j++) {System.out.print ("*");}16 System.out.println (); 17}18}19/ /print parallelogram private static void Printpxsbx () {(int i=1;i<=5;i++) {for (Int. k=1;k<=5-i;k + +) {System.out.print (""),}25 for (int j=1;j<=5;j++) {-Sy Stem.out.print ("*");}28 System.out.println (); 29}30}31//print triangle + private s tatic void Printsjx () {for (int i=1;i<=5;i++) {k=1;k<=5-i;k++ Stem.out.print ("");}37 for (int j=1;j<=2*i-1;j+ +) {System.out.print ("*"),}40 System.out.println (), 41}42 43 }44 45}

  

J2SE 1.5 provides another form of a for loop. With this form of for loop, you can iterate over objects of types such as arrays and collection in a simpler way. This article describes how to use this loop in a specific way, explaining how to define a class that can be traversed like this, and explain some common issues with this mechanism.

In a Java program, to "process"-or, "traverse"-an array or an element in a collection, it is generally implemented with a for loop (of course, it is not possible to use other kinds of loops, but it is not known because the length of the word for is shorter, Or because the meaning of the word for is compared with this kind of operation, at this time the for loop is much more common than other loops.

1: Traditional way of traversing an array

/* Create an array */int[] integers = {1, 2, 3, 4}; /* start to traverse */for (int j = 0; J < Integers.length, J + +) {     int i = integers[j];     

  

2: Traditional way to traverse collection objects

/* Create a collection */string[] strings = {"A", "B", "C", "D"}; Collection stringlist = java.util.Arrays.asList (strings); /* Start traversing */for (Iterator ITR = Stringlist.iterator (); Itr.hasnext ();) {     Object str = Itr.next ();     System.out.println (str); }

  

In the latest version of the Java language, ――j2se 1.5, another form of a for loop has been introduced. With this form of a for loop, it is now possible to traverse the work in a simpler way.

Not strictly speaking, the second type of Java for loop is basically this format:

for (loop variable type loop variable name: object to be traversed) loop body

With this syntax, an operation that iterates through an array can be written like this:

3: An easy way to iterate through an array

/* Create an array */int[] integers = {1, 2, 3, 4}; /* Start traversing */for (int i:integers) {     System.out.println (i);/* output "1", "2", "3", "4" */} in turn

  

4: Equivalent code for a simple way to traverse an array

/* Create an array */int[] integers = {1, 2, 3, 4}; /* Start traversing */for (int variable name a = 0; variable name < integers.length; variable name A + +) {     System.out.println (integers[variable name a]);/* output "1", "2", "3", "4" */}5: Simple way to traverse collection/* Create a collection */string[] strings = {"A", "B", "C", "D"}; Collection list = java.util.Arrays.asList (strings); /* Start traversing */for (Object str:list) {     System.out.println (str);/* output "A", "B", "C", "D" */} in turn

  

While loop

While is the most basic cycle, in English the word "while" means "when", and in Java programming, it can also be understood as "when", its structure is:

while (Boolean expression) {//looping content}

  

As long as the Boolean expression is true, the loop experience continues.

Instance
public class Test {public   static void Main (String args[]) {      int x = ten;      while (x <) {         System.out.print ("Value of x:" + x);         x + +;         System.out.print ("\ n");}}   

The results of the above example compilation run as follows:

Value of X:10value of X:11value of X:12value of X:13value of X:14value of X:15value of X:16value of X:17va Lue of X:18value of x:19

  

Do/while statements

Before you learn the Do/while statement, you should know how the while statement works. The while statement performs a conditional judgment before executing the loop body inside the curly braces.

For a while statement, you cannot enter a loop if the condition is not met. But sometimes we need to do it at least once, even if we don't meet the conditions.

The Do...while loop is similar to the while loop, but the Do...while loop executes at least once.

do {       //code statement}while (boolean expression);

Example: Calculate the result of a 1+2+3+4......+100.

public class Control5{public static void Main (string[] args) {int a=1,result=0;do{result+=a++;} while (a<=100); SYSTEM.OUT.PRINTLN (result);}}

Output Result:

5050

  Note: in fact, in the actual program development, Do/while loop statements are not often used. Because this statement is the first to perform the cyclic body re-detection conditions, so there will be some dangerous data without detection, will be executed. We recommend that you use a while statement or a For loop statement to write code.

Dark Horse Programmer--java Foundation--Selection, cycle

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.