首页 > 代码库 > java中的if....else 结构

java中的if....else 结构

判断是素数,还是偶数?

import java.util.Scanner;

public class Boke3 {
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.println("请输入一个数字:");
    int num = input.nextInt();
    if(num%2==0){
      System.out.println(num+"是偶数");
    }else{
      System.out.println(num+"是奇数");
    }
  }
}

根据成绩输出对应的等级,使用if多分支和switch语句分别实现

a:用if和else来实现.

import java.util.Scanner;
public class Boke4 {
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.println("请输入你的分数:");
    int num = input.nextInt();
    String grade;
    if(num>90){
      grade = "A";
    }else if(num>80){
      grade = "B";
    }else if(num>70){
      grade = "C";
    }else if(num>60){
      grade = "D";
    }else{
      grade = "E";
    }
    System.out.println("成绩为"+num+"属于"+grade+"级");
  }
}

b:用swith来实现.

import java.util.Scanner;
public class Boke4 {
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.println("请输入你的分数:");
    int num = input.nextInt();
    String grade;
    switch(num/10){
      case 10:
      case 9:
        grade="A";
        break;
      case 8:
        grade="B";
        break;
      case 7:
        grade="C";
        break;
      case 6:
        grade="D";
        break;
      default:
        grade="E";
     }

     System.out.println("成绩为"+num+"属于"+grade+"级");
   }
}

java中的if....else 结构