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

โปรแกรม Java รับข้อมูลจากผู้ใช้ (Scanner)

ในบทความนี้ เราจะเรียนรู้วิธีรับข้อมูลจากผู้ใช้ในภาษา Java โดยใช้คลาส Scanner

เมธอดหลักของ Scanner

เมธอดคืนค่าคำอธิบาย
next()Stringอ่านคำเดียว (จนถึง space)
nextLine()Stringอ่านบรรทัดเต็ม (รวม space)
nextInt()intอ่านจำนวนเต็ม
nextDouble()doubleอ่านทศนิยม
nextBoolean()booleanอ่าน true/false

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

อินพุต:

Hello, I am John!

เอาต์พุต:

The input string is: Hello, I am John!

อัลกอริทึม

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

ตัวอย่างที่ 1: ใช้ Scanner (แนะนำ)

import java.util.Scanner;

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

        Scanner scanner = new Scanner(System.in);
        System.out.println("A reader object has been defined");
        System.out.print("Enter a string: ");
        value = scanner.nextLine();

        System.out.println("The nextLine method is used to read the string value");
        System.out.println("The string 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);
    }
}

ข้อแตกต่าง

  • Scanner: ใช้ง่าย มีเมธอดมาก รองรับทุกชนิดข้อมูล
  • BufferedReader: เร็วกว่าสำหรับอ่านไฟล์ขนาดใหญ่ แต่ต้อง parse เอง
  • ในปัจจุบันแนะนำใช้ Scanner สำหรับโปรแกรมทั่วไป