溫馨提示×

java nextint用法 能否組合使用其他方法

小樊
96
2024-11-25 15:58:51
欄目: 編程語言

當然可以。nextInt()Scanner 類的一個方法,用于從輸入流中讀取下一個整數。你可以在一個 Scanner 對象上調用 nextInt() 方法,并在需要時組合使用其他方法。以下是一些示例:

  1. 使用 nextInt()nextLine() 方法:
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("請輸入一個整數:");
        int number = scanner.nextInt();

        System.out.print("請輸入一個字符串:");
        scanner.nextLine(); // 清除緩沖區中的換行符
        String text = scanner.nextLine();

        System.out.println("輸入的整數是:" + number);
        System.out.println("輸入的字符串是:" + text);
    }
}

在這個示例中,我們首先使用 nextInt() 方法讀取一個整數,然后使用 nextLine() 方法讀取一個字符串。注意,在調用 nextInt() 之后,我們需要調用 nextLine() 方法來清除緩沖區中的換行符,否則 nextLine() 將返回一個空字符串。

  1. 使用 nextInt()hasNextInt() 方法:
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("請輸入一個整數:");
        while (!scanner.hasNextInt()) {
            System.out.print("輸入錯誤,請輸入一個整數:");
            scanner.next(); // 清除緩沖區中的非整數輸入
        }
        int number = scanner.nextInt();

        System.out.println("輸入的整數是:" + number);
    }
}

在這個示例中,我們使用 hasNextInt() 方法檢查輸入流中是否有下一個整數。如果沒有,我們提示用戶重新輸入,并使用 next() 方法清除緩沖區中的非整數輸入。當用戶輸入一個整數時,我們調用 nextInt() 方法讀取它。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女