这篇文章主要讲解了如何使用Java中的判断结构、选择结构、循环结构,内容清晰明了,对此有兴趣的小伙伴可以学习一下,相信大家阅读完之后会有帮助。
判断结构:
- java中使用if作为判断结构
- if语句有三种格式:
package study.program_struct;
import java.util.Scanner;
public class if_useage {
public static void main(String args[]){
int i;
Scanner reader=new Scanner(System.in);
i=reader.nextInt();
if(i>=90){
System.out.println("i>=90");
}else if (i>60){
System.out.println("60<i<90");
}else{
System.out.println("i<=60");
}
}
}
选择结构:
- java使用switch语句来构成选择结构
- switch语句的格式:
- switch语句选择的类型只有四种:byte,short,int,char【即上面的i只能为这几种,1.7进行了扩展,可以采用一些特殊类型如枚举类型,String】
- 匹配到结果后,需要使用break来退出,不然会向下顺序执行完所有选择
package study.program_struct;
import java.util.Scanner;
public class switch_useage {
public static void main(String args[]){
int i;
Scanner reader=new Scanner(System.in);
i=reader.nextInt();
switch (i){
case 1:System.out.println("1");break;
case 2:System.out.println("2");break;
case 3:System.out.println("3");break;
case 4:System.out.println("4");break;
default:System.out.println("default");
}
}
}
循环结构:
- java中有三种循环结构:while,do-while,for
while:
- while语句的格式:

package study.program_struct;
public class While_usage {
public static void main(String args[]){
int i=5;
while(i>0){
System.out.println(i);
i=i-1;
}
}
}
do-while:
- do-while语句的格式:

- do-while特定:无论条件是否满足,循环体至少执行一次。
package study.program_struct;
public class While_usage {
public static void main(String args[]){
do {
System.out.println("hello");
}while (false);
}
}
for:
- for语句格式:

package study.program_struct;
public class For_usage {
public static void main(String args[]){
for (int i=0;i<5;i++){
System.out.println(i);
}
}
}
补充:
for-each:
- for each结构是jdk5.0新增加的一个循环结构)

- 定义一个变量用于暂存集合中的每一个元素,并执行相应的语句。
- 集合表达式(int 副本:原本)必须是一个数组或者是一个实现了lterable接口的类(例如ArrayList)对象。
- 缺点: 无法对指定下标操作或难以对指定下标操作。

break和continue:
- break可以用来跳出选择结构和循环结构
- continu可以用来打断循环结构中的当次循环,直接进行下一次循环。

package study.program_struct;
public class For_usage {
public static void main(String args[]){
for (int i=0;i<5;i++){
if(i%2==0)continue;
System.out.println(i);// 1,3
}
}
}
使用return来结束方法:
java中也可以使用return来中断循环。
看完上述内容,是不是对如何使用Java中的判断结构、选择结构、循环结构有进一步的了解,如果还想学习更多内容,欢迎关注天达云行业资讯频道。