java学习day4
程序员文章站
2022-07-14 17:29:14
...
Switch and case
由于case穿透性,一般都要在每个case后break。
public class Demo3 {
public static void main(String[] args) {
char grade='C';
switch (grade){
case 'A':
System.out.println("优秀");
break;
case 'B':
System.out.println("良好");
break;
case 'C':
System.out.println("及格");
break;
case 'D':
System.out.println("再接再厉");
break;
case 'E':
System.out.println("挂科");
break;
default:
System.out.println("未知等级");
}
}
}
for 循环两个例子
输出一份九九乘法表
public class MultiExcel {
public static void main(String[] args) {
for (int j=1;j<=9;j++){
for (int i=1;i<=j;i++){
System.out.print(j+"*"+i+"="+(j*i)+"\t");
}
System.out.println();
}
}
}
两种语法对比,后一种结构为增强for循环
public class Demo7 {
public static void main(String[] args) {
int[] numbers={10,20,30,40,50};
for (int i=0;i<5;i++){
System.out.println(numbers[i]);
}
System.out.println("=============================");
for (int x:numbers){
System.out.println(x);
}
}
}
Break and continue
break用于退出循环。
package struct;
public class BreakDemo {
public static void main(String[] args) {
int i=0;
while(i<100){
i++;
System.out.println(i);
if (i==30){
break;
}
}
System.out.println("123");
}
}
continue终止某次循环过程,类似于跳过某次循环。
package struct;
public class ContinueDemo {
public static void main(String[] args) {
int i=0;
while (i<100){
i++;
if (i%10==0){
System.out.println();
continue;
}
System.out.println(i);
}
}
}
输出101到150间质数
package struct;
public class LabelDemo {
public static void main(String[] args) {
int count=0;
outer:for (int i=101;i<150;i++){
for (int j=2;j<i/2;j++){
if (i%j==0){
continue outer;
}
}
System.out.println(i+"");
}
}
}
练习
打印三角形
package struct;
public class DrawDemo {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
for (int j = 5; j >= i; j--) {
System.out.print(" ");
}
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
for (int j = 1; j < i; j++) {
System.out.print("*");
}
System.out.println();
}
}
}
上一篇: JAVA学习 Day4
下一篇: 【mysql学习】day4