热门搜索 :
考研考公
您的当前位置:首页正文

基础Java语句

来源:东饰资讯网

Patterns

Sum 语句

Goal: Find the sum of a collection of items.

<type> sum = 0;
<for each item>
{
    sum += <item>;
}

Example:

int sum = 0;
for(i = 0; i < 10; i++) {
    sum += i;
}

Output 语句

Goal: Show a value to the user.

System.out.println("<Label>" + <Value>);

Example:

System.out.println("Age is" + age);
System.out.println("Name is" + name);

Read 语句

Goal: Read a value from the user.

System.out.print("<prompt>");
<type> <varible> = <read operation>;

or,

System.out.print("<prompt>");
<type> <varible> = <read operation>; // if varible has already been declared.

Example:

System.our.print("Age: ");
int age = In.nextInt();

Class.In:

public static int nextInt()    // Read a Integer.
public static double nextDouble()    // Read a Double
public static char nextChar()    // Read a char
public static String nextLine()    // Read String

Read loop 语句

Goal: Read values until the user enters an "end of input" value.

<Read pattern>
while(<value> != <end value>) {
    <use the value>
    <read pattern>
}

Example:

int sum;
int i = In.nextInt();
while(i != -1) {
    sum += i;
    int i = In.nextInt();
}

Array loop 语句

Goal: Loop over items in an array.

for(int i = 0; i < <array>.length; i++>) {
    <use the item array[i]>
}

Example:

int[] list = new int[5];
for(int i; i < list.length; i++>) {
    System.out.println(list[i]);
}

Count 语句

Goal:
without guard: Count the number of items in a collection.
with guard: Count the number of items that satisfy a collection.

// Without guard
int count = 0;
<for each item>

// With guard:
int count = 0;
<for each item>
    if(<guard>)
        count++;

Example:

// Without guard
String[] names = {Adam, Bob, Christina, David, Eva};
int count = 0;
for(i = 0; i < names.length; i++>)
    count++;

// With guard:
String[] names = {Adam, Bob, Christina, David, Eva};
int count = 0;
for(i = 0; i < names.length; i++>)
    if(names[i].length <= 4>)
        count++;
Top