Câu lệnh if else trong Java

Câu lệnh if else dạng tổng quát

if(biểu thức 1)
{
    Khối lệnh 1;
}
else
{
    Khối lệnh 2;
}

Nếu biểu thức 1 có giá trị true (boolean) thì chương trình sẽ thực hiện khối lệnh 1 trong câu lệnh if.
Nếu biểu thức 1 có giá trị false (boolean) thì chương trình sẽ thực hiện khối lệnh 2.

Ví dụ 1: Nhập vào 1 số nguyên num. Nếu num < 0, in ra màn hình console chuỗi “The integer is negative”. Nếu num > 0, in ra chuỗi “The integer is positive”

package net.vncoding;

import java.util.Scanner;

public class MultipleBranches {

    public static void main(String[] args) {
        
        System.out.print("Enter an integer:");

        Scanner sc = new Scanner(System.in);
        int num = sc.nextInt();

        if (num < 0) {
            System.out.println("The integer is negative");
        } else {
            System.out.println("The integer is positive");
        }
        sc.close(); 
    }
}

Kết quả:
Enter an integer: 4
The integer is positive

Enter an integer:-3
The integer is negative

Lệnh if khuyết lệnh else

if(biểu thức 1)
{
    Khối lệnh 1;
}

Nếu biểu thức 1 có giá trị true thì khối lệnh 1 sẽ được thực hiện
Nếu biểu thức 1 bằng false thì khối lệnh 1 không được thực hiện

Ví dụ 2: Nhập vào 1 số nguyên num. Nếu num < 0, in ra màn hình console chuỗi “The integer is negative”. Nếu num <= 0, thì không in chuỗi ra màn hình.

MultipleBranches.java

package net.vncoding;

import java.util.Scanner;

public class MultipleBranches {

    public static void main(String[] args) {
        
        System.out.print("Enter an integer:");

        Scanner sc = new Scanner(System.in);
        int num = sc.nextInt();

        if (num < 0) {
            
            System.out.println("The integer is negative");
        }
        sc.close(); 
    }
}

Kết quả:
Enter an integer:6

Enter an integer:-9
The integer is negative

Lệnh else if

Khi ta muốn chọn 1 trong n quyết định ta dùng lệnh sau.

if(biểu thức 1)
{
    Khối lệnh 1;
}
else if(biểu thức 2)
{
    Khối lệnh 2;
}
…
else
{
    Khối lệnh n;
}

Ví dụ 3: Yêu cầu giống ví dụ 1. Bổ sung thêm, nếu num = 0, in ra chuỗi “The integer equals to zero”.
MultipleBranches.java

package net.vncoding;

import java.util.Scanner;

public class MultipleBranches {

    public static void main(String[] args) {
        
        System.out.print("Enter an integer:");

        Scanner sc = new Scanner(System.in);
        int num = sc.nextInt();

        if (num < 0) {
            
            System.out.println("The integer is negative");
        } else if (num == 0) {
            
            System.out.println("The integer equals to zero");            
        } else {
            
            System.out.println("The integer is positive");
        }
        sc.close(); 
    }
}

Kết quả:
Enter an integer:3
The integer is positive

Enter an integer:-9
The integer is negative

Enter an integer:0
The integer equals to zero

Be the first to comment

Leave a Reply