Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

โปรแกรม Java อ่านตัวเลขจาก Standard Input

ในบทความนี้ เราจะเรียนรู้วิธีอ่านตัวเลขจาก Standard Input ในภาษา Java โดยใช้ Scanner.nextInt()

ตัวอย่างการทำงาน

อินพุต:

55

เอาต์พุต:

The input value is 55

อัลกอริทึม

  1. เริ่มต้นโปรแกรม
  2. ประกาศตัวแปร int: value
  3. สร้าง Scanner object
  4. พรอมป์ผู้ใช้กรอกตัวเลข
  5. อ่านค่าด้วย nextInt()
  6. แสดงผลลัพธ์
  7. จบโปรแกรม

ตัวอย่างที่ 1: ใช้ Scanner

import java.util.Scanner;

public class PrintNumber {
    public static void main(String[] args) {
        int value;

        System.out.println("Required packages have been imported");
        System.out.println("Variable to store value is defined");
        Scanner reader = new Scanner(System.in);
        System.out.println("A reader object has been defined");
        System.out.print("Enter a number: ");
        value = reader.nextInt();

        System.out.println("The nextInt method is used to read the number");
        System.out.println("The number is: ");
        System.out.println(value);
    }
}

ตัวอย่างที่ 2: ใช้ BufferedReader

import java.io.*;

public class ReadNumber {
    public static void main(String args[]) throws IOException {
        InputStreamReader read = new InputStreamReader(System.in);
        System.out.println("An object of InputStreamReader class is created");
        BufferedReader in = new BufferedReader(read);
        System.out.println("A constructor of the BufferedReader class is created");
        System.out.println("Enter a number: ");
        int number = Integer.parseInt(in.readLine());
        System.out.println("The number is: " + number);
    }
}

ข้อควรระวัง

  • nextInt() อ่านแค่ตัวเลข ไม่ consume newline character
  • ถ้าป้อนข้อมูลผิดรูปแบบ (เช่น พิมพ์ "abc") จะโยน InputMismatchException
  • ควรใช้ try-catch หรือ hasNextInt() ตรวจสอบก่อนอ่าน

ตัวอย่างป้องกันข้อผิดพลาด

Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
if (sc.hasNextInt()) {
    int num = sc.nextInt();
    System.out.println("You entered: " + num);
} else {
    System.out.println("Invalid input! Please enter an integer.");
    sc.next(); // clear invalid token
}