Java学习-Day5

while 语句

一、while 和 for

while 语句本质上比 for 更基础, 因此可以替代后者. 但 for 在很多时候更方便.

for 循环方便是因为控制循环的语句在开始就已经声明,而 while 循环需要在循环内部更新数据或使用 if-else 语句进行判断后使用 break 跳出当前循环体.

break 语句又出现了, 上次是在 switch 语句里. 都是表示跳出当前循环体. 当然 break 对 for 循环也同样适用.

二、示例

示例描述

给定一个上界,从1开始求和,取和小于上界的最大值.

输入

一个正整数表示的上界

输出

小于上界和的最大值

具体代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package test;

/**
* This is the ninth code. Names and comments should follow my style strictly.
*
* @author Shihuai Wen wshysxcc@outlook.com.
*/
public class WhileStatement {

/**
*********************
* The entrance of the program.
*
* @param args Not used now.
*********************
*/
public static void main(String args[]) {
whileStatementTest();
}// Of main

/**
*********************
* The sum not exceeding a given value.
*********************
*/
public static void whileStatementTest() {
int tempMax = 100;
int tempValue = 0;
int tempSum = 0;

// Approach 1.
while (tempSum <= tempMax) {
tempValue++;
tempSum += tempValue;
System.out.println("tempValue = " + tempValue + ", tempSum = " + tempSum);
} // Of while
tempSum -= tempValue;

System.out.println("The sum not exceeding " + tempMax + " is: " + tempSum);

// Approach 2.
System.out.println("\r\nAlternative approach.");
tempValue = 0;
tempSum = 0;
while (true) {
tempValue++;
tempSum += tempValue;
System.out.println("tempValue = " + tempValue + ", tempSum = " + tempSum);

if (tempMax < tempSum) {
break;
} // Of if
} // Of while
tempSum -= tempValue;

System.out.println("The sum not exceeding " + tempMax + " is: " + tempSum);
}// Of whileStatementTest
}// Of class WhileStatement

运行截图

综合任务 1

一、任务描述

找出成绩最好、最差的同学。但有挂科的同学不参加评比.

二、任务要求

数据要求

进行学生成绩的随机生成, 区间为 [50, 100].

数据存放

学生的成绩存放于一个矩阵,其中行表示学生,列表示科目。如:第 0 行表示第 0 个学生的数学、语文、英语成绩。如下所示.

1
2
3
4
5
6
7
    数学 语文 英语 ...
0 1 2
0 79 83 91
1 ... ... ...
2 ... ... ...
3 ... ... ...
...

三、实现

输入

使用随机生成的在区间 [50, 100]的整数填充的矩阵

输出

矩阵各行和的值最小和最大的行编号(从0开始)

具体代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package test;

import java.util.Arrays;
import java.util.Random;

/**
* This is the tenth code, also the first task.
*
* @author Shihuai Wen wshysxcc@outlook.com.
*/
public class Task1 {

/**
*********************
* The entrance of the program.
*
* @param args Not used now.
*********************
*/
public static void main(String args[]) {
task1();
}// Of main

/**
*********************
* Method unit test.
*********************
*/
public static void task1() {
// Step 1. Generate the data with n students and m courses.
// Set these values by yourself.
int n = 10;
int m = 3;
int lowerBound = 50;
int upperBound = 100;
int threshold = 60;

// Here we have to use an object to generate random numbers.
Random tempRandom = new Random();
int[][] data = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
data[i][j] = lowerBound + tempRandom.nextInt(upperBound - lowerBound);
} // Of for j
} // Of for i

System.out.println("The data is:\r\n" + Arrays.deepToString(data));

// Step 2. Compute the total score of each student.
int[] totalScores = new int[n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (data[i][j] < threshold) {
totalScores[i] = 0;
break;
} // Of if

totalScores[i] += data[i][j];
} // Of for j
} // Of for i

System.out.println("The total scores are:\r\n" + Arrays.toString(totalScores));

// Step 3. Find the best and worst student.
// Typical initialization for index: invalid value.
int tempBestIndex = -1;
int tempWorstIndex = -1;
// Typical initialization for best and worst values.
// They must be replaced by valid values.
int tempBestScore = 0;
int tempWorstScore = m * upperBound + 1;
for (int i = 0; i < n; i++) {
// Do not consider failed students.
if (totalScores[i] == 0) {
continue;
} // Of if

if (tempBestScore < totalScores[i]) {
tempBestScore = totalScores[i];
tempBestIndex = i;
} // Of if

// Attention: This if statement cannot be combined with the last one
// using "else if", because a student can be both the best and the worst.
if (tempWorstScore > totalScores[i]) {
tempWorstScore = totalScores[i];
tempWorstIndex = i;
} // Of if
} // Of for i

// Step 4. Output the student number and score.
if (tempBestIndex == -1) {
System.out.println("Cannot find best student. All students have failed.");
} else {
System.out.println("The best student is No." + tempBestIndex + " with scores: "
+ Arrays.toString(data[tempBestIndex]));
} // Of if

if (tempWorstIndex == -1) {
System.out.println("Cannot find worst student. All students have failed.");
} else {
System.out.println("The worst student is No." + tempWorstIndex + " with scores: "
+ Arrays.toString(data[tempWorstIndex]));
} // Of if
}// Of task1

}// Of class Task1

运行截图

常见问题

实际代码中,for 和 if 是最常见的, switch 和 while 使用少得多.

使用了 continue, 它是指继续跳过本次循环后面的代码,直接进入下一次循环. 而 break 是跳出整个循环体.

if-else 应该保持对同一个表达式或变量的值进行判断。当有多变量的时候尽量多写几个if-else 保持代码可读性,毕竟人脑能考虑到的情况是有局限性的。

总结

结合了之前所有的知识点。相比起枯燥乏味的示例,实际解决一个问题更加能够提升自己的能力,尤其是在代码出现问题时候进行的Debug操作。

最后要相信人脑的局限性,要像计算机一样思考才能写出更好的代码。