了解Java中的决策和分支

72 阅读6分钟

了解Java中的决策和分支

Java语句是以顺序的方式执行的,也就是说,它们的排列顺序。然而,在有些情况下,必须改变这种顺序以满足特定的要求。在这种情况下,需要做出决定,告诉计算机要执行哪些语句。

当程序打破或不遵守顺序,而是跳转到代码的另一部分时,就会发生分支。在条件性分支中,计算机通常遵循某些预定的条件。

前提条件

要想跟着学习,你需要有一些Java的基本知识。此外,你必须能够使用[Netbeans]和[Intellij]等IDE。

使用if语句进行决策

if 语句是受控监督下的决策语句的一个例子。它也是一个双轨决策语句,与表达式结合使用。

使用if 语句时,程序的执行取决于结果是真还是假。

if 语句的结构和语法如下所示。

if(test expression){
    statement-block:
}

statement-x:

statement-block 可以是单个或一组语句,只有当测试表达式为真时才会执行。

下面是另一个if 语句的例子。

if (category==mathematics){
    marks = marks+bonus_marks; // statement block
}
system.out.println(marks)

程序检查category 类型是否为mathematics 。如果是true ,那么额外的奖金_标记将被添加到学生的分数中。

if-else语句

if-else 条件可以被看作是if 语句的一个进步,因为if-else 语句与if 语句相比只有一些升级。

下面是if-else 语法的样子。

if(test expression){
    //block of true statement
}else{
    //block of false statement
}
statement-x

如果测试表达式是true ,就执行true-statement-block。如果不是,则执行false-code-block。这就是说,必须有一个条件被执行。

考虑一下这个if-else 的例子。

if (gender==male){
  boy=boy+1
}else{
  girl=girl+1
}

如果gendermale ,那么就执行boy=boy+1 语句。else 部分被跳过,因为该表达式为真。

如果genderfemale ,那么语句boy=boy+1 将被跳过,而else 部分为girl=girl+1 被执行。

下面的程序使用一个if-else 语句来检查一个输入的数字是奇数还是偶数。

import java.util.Scanner;

public class EvenOddnumbers {

    public static void main(String args[]) {

        Scanner reader = new Scanner(System.in);

        System.out.print("Enter any number: ");
        int num = reader.nextInt(); // getting user input using the scanner class

        if(num % 2 == 0){ //checks if number is divisible by 2 and has no remainder through modulo function
            System.out.println(num + " Number is even"); // Output when number is even
        }else{
            System.out.println(num + " Number is odd"); // Output when number is odd
        }
    }
}

这个程序的输出将被给出,并说明它是偶数还是奇数。

使用if-else 语句,我们可以检查当前年份是否为闰年。

import java.util.*;
public class main {

   public static void main(String args[]) {
      String months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", 
         "Oct", "Nov", "Dec"};
      
      int year;
      // Create a Gregorian calendar initialized
      // with the current date in the
      // default locale and timezone.
      
      GregorianCalendar gcalendar = new GregorianCalendar();
      
      // Display current  date information.
      System.out.print("Date: ");
      System.out.print(months[gcalendar.get(Calendar.MONTH)]);
      System.out.print(" " + gcalendar.get(Calendar.DATE) + " ");
      System.out.println(year = gcalendar.get(Calendar.YEAR));
      
      // Test if the current year is a leap year
      if(gcalendar.isLeapYear(year)) {
         System.out.println("The current year is a leap year");
      }else {
         System.out.println("The current year is not a leap year");
      }
   }
}

该程序将根据公历输出当前日期,并说明它是否是闰年。

嵌套的if-else语句

嵌套的if-else 语句是在必须涉及到一些决定的时候使用的。

下面是一个嵌套的if-else 语句的结构。

if(test condition a){
    if(test condition b){
        //statement-1;
    }else{
        //statement-2;
    }
}else{
    //statement-3;
}

statement-x;

如果test condition afalse ,那么将执行statement-3

另一方面,如果test condition atrue ,程序就会进入test condition b 并执行预定义的条件。

下面的例子使用了一个nested if-else 语句。

public class Largest {
  public static void main(String[] args) {
        int i=40, j=23, k=50; //defining variables and assignment them values

        System.out.println("largest value is:");
        if (i>j){
            if (i>k){ //first nested if-else statement
                System.out.println(i);
            }else{
                System.out.println(k);
            }

        }else{

           if(j>k){ //second nested if-else statement
                System.out.println(k);
            }else{
                System.out.println(j);
            }
        }
    }
}

上述程序将显示最大的数字,即50

else-if 梯子

当需要使用多路径决策时,else-if 梯子就会出现。

下面是一个else if 语句的语法。

if(condition m)
{
  statement-a;
  }
  else if(condition n)
  {
  statement-b;
  }
  else if(condition o)
  {
  statement-c;
  }
  else if(condition p)
  {
  statement-n;
  }
  else
  {
  default-statement;
}
statement-x;

这些条件按逻辑顺序从第一个条件到最后一个条件进行评估,当发现一个真实的条件时,就会执行。

当没有条件被执行时,包含default-statement 的最后一个else 语句被执行。

让我们使用else-if 语句来创建一个简单的程序来给学生评分。

public class Main {
  public static void main(String[] args) {
   int marks = 22;

    if (marks >= 79) { //if a students marks are greater than 79
      System.out.println("First upper."); 
    } else if (marks >= 59 && marks < 79) { //if marks are greater than 59 but less than 79
      System.out.println("Second upper.");
    } else if(marks >= 49 && marks < 59) { //if marks are greater than 49 but less than 59
      System.out.println("Second lower.");
    } else if(marks < 49){
    System.out.println("fail");
    }
  }
}

开关语句

switch 语句将一个变量与一个可能的值的列表进行比较。

当检测到匹配时,就会执行与该情况相关的语句块。

switch 语句的一般结构如下。

switch (expression)
{
    case value-1:
      block-statement 1;
    break;
    case value-2:
      block-statement 2;
    break;
    default:
      default block statement;
    break;
}
statement-x;

case 标签是常量表达式,应该始终是唯一的。

在一个switch 语句中,case labels 被一个完整的冒号(:)分开。

当运行switch 代码块时,expression 的值将与提供的case 标签进行比较。如果case 值与表达式相匹配,则执行该case 中的代码块,循环中断。

如果在任何一个case 标签中没有找到match ,则执行default 值。

下面是一个使用switch 语句来确定星期的程序的例子。

public class Main {
  public static void main(String[] args) {
    int day = 8;
    switch (day) {
      case 1: //if day is 1
        System.out.println("Monday");
        break;
      case 2://if day is 2
        System.out.println("Tuesday");
        break;
      case 3://if day is 3
        System.out.println("Wednesday");
        break;
      case 4://if day is 4
        System.out.println("Thursday");
        break;
      case 5://if day is 5
        System.out.println("Friday");
        break;
      case 6://if day is 6
        System.out.println("Saturday");
        break;
      case 7://if day is 7
        System.out.println("Sunday");
        break;
        default://if the number is not in case labels
        System.out.println("enter valid day");
        break;
    }
  }
}

上述程序的输出将是enter valid day ,因为8不在定义的案例标签内。

if-else语句和switch语句的区别

  1. switch语句有许多情况需要测试,其中所有情况都可能不正确,促使系统显示默认语句,而if-else语句只有两条语句需要执行,其中一条是表达式的真,另一条是表达式的假,没有默认语句。
  2. 在switch语句中,值取决于用户的选择,并且根据值和案例标签的匹配来执行案例,而if-else语句中的值是基于为if或else块设置的条件。

if-else语句和switch语句的相似之处

  1. 当发现一个真正的匹配时,该语句的执行就结束了。对于switch 语句,当发现case标签之间的匹配时,对于if-else 语句,当发现条件的真正匹配时。
  2. 它们被用来控制程序的流程。

总结

决策语句是非常有用的,特别是在必须满足某个条件的情况下。当我们想对用户的数据进行分类时,它们也很有帮助。因此,你可以利用这些知识来制作更强大的应用程序。