记录11.25的学习内容
1.利用while(){}来实现一个if语句的循环
if语句只会执行一遍,如果想在if最后一个判断条件之后再次从头开始执行if语句的话,可以利用while(){}来实现。
可以参考下面这个最简单的计算器
public class Calculator {
public static void main(String[] args) {
while (true) {
Scanner scanner = new Scanner(System.in);
System.out.println("输入三个数,第二个数为四则运算符号(1 = +,2 = -,3 = *,4 = /)。");
int i = scanner.nextInt();
int j = scanner.nextInt();
int k = scanner.nextInt();
int m;
if(j == 1) {
m = i + k;
} else if (j == 2) {
m = i - k;
} else if (j == 3) {
m = i * k;
} else {
m = i / k;
}
System.out.println(m);
System.out.println("输入0继续,输入T离开!");
String a = scanner.next();
String b = "t";
if (a.hashCode() != b.hashCode()) {
} else {
System.out.println("输入了t,再见");
break;
}
}
}
}
总结一下格式
while(true){
......
......
if(...){ //主代码
...
...
}else{
...
}
if(...){ //用于判断
...
}else{
...
}
}
2.Switch语句的格式
switch (变量)
{
case 1:
System.out.println("语句1(语句体部分可以是一条或多条语句)");
break;
case 2:
System.out.println("语句2");
break;
default:
System.out.println("语句n(表示所有情况都不匹配的时候,就执行该处的内容,和if语句的else相似。)");
}
case后面跟的1,2,3,4并不是代表顺序的意思,而是要和表达式进行比较的值。
例如:
想要表示今天星期几,在switch语句之前就会有
`Scanner scanner = new Scanner(System.in);
System.out.println(“请输入一个数字(1-7):”);
int i= scanner.nextInt();
再输入对应的1234567中的一个,执行switch语句,得出今天星期几。
当然也可以写case 50,case 500,case 5000 , 都是可以的。
3.遍历
作用:
简单来说,遍历就是把一个数组,字符串,集合每个元素,字符都查一遍。遍历也是数组操作中的基石。
遍历的代码演示:
int[] arr = { 1, 2, 3, 4, 5 };
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
for (int i = 0; i < arr.length; i++) {// 正序输出
System.out.println(arr[i]);
}
for (int i = arr.length - 1; i >= 0; i--) {// 倒序输出
System.out.println(arr[i]);
}
输出的结果:
1
2
3
4
5
1
2
3
4
5
5
4
3
2
1
11.26 阴