推荐学习:《java视频教程》
流程控制
JAVA输入输出
输入
两种输入方法:
public class a { public static void main(String[] args) { var sc = new Scanner(System.in); System.out.println("请输入姓名:"); String name = sc.nextLine(); System.out.printf("%n欢迎你:%s", name); }}
结果:
public class a { public static void main(String[] args) { String w = JOptionPane.showInputDialog("请输入词汇:"); System.out.println(w); }}
结果:
输出
代码演示:
public class a { public static void main(String[] args) { int w = 1; int a = 2; System.out.print(w); System.out.print(a); }}
结果:
public class a { public static void main(String[] args) { int w = 1; int a = 2; System.out.println(w); System.out.println(a); }}
结果:
public class a { public static void main(String[] args) { int w = 1; int a = 2; System.out.printf("w=%d a=%d", w, a); }}
结果:
分支语句
if else
public class a { public static void main(String[] args) { if (1>2){ System.out.println("A"); }else { System.out.println("B"); } }}
public class a { public static void main(String[] args) { if (1 > 2) { System.out.println("A"); } else if (1 > 0) { System.out.println("B"); } else { System.out.println("C"); } }}
switch case default
public class a { public static void main(String[] args) { int w=1; String wk = ""; switch (w) { case 2: wk = "星期一"; break; case 3: wk = "星期二"; break; case 4: wk = "星期三"; break; case 5: wk = "星期四"; break; case 6: wk = "星期五"; break; case 7: wk = "星期六"; break; default: wk = "星期日"; break; } System.out.println(wk); }}
结果:
循环语句
for
public class a { public static void main(String[] args) { for (int i = 0; i < 5; i++) { System.out.println(i); } }}
结果:
for in
public class a { public static void main(String[] args) { int[] a = {1, 2, 3, 4, 5}; for (int i : a) { System.out.println(i); } }}
while do while
public class a { public static void main(String[] args) { int i = 0; while (i < 5) { i++; System.out.println(i); } }}
结果:
public class a { public static void main(String[] args) { int i = 0; do { i++; System.out.println(i); } while (i < 0); }}
结果:
break continue
int i = 0;while (++i < 20) { if (i % 2 == 0) continue; System.out.println(i); if (i > 10) break;}
推荐学习:《java视频教程》
以上就是完全掌握JAVA流程控制的详细内容,更多请关注php中文网其它相关文章!