株所实习第九天(while,switch,遍历)

记录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 阴

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值