Scanner 是Java5中新增的一個簡單文本掃描器,可以用於獲取用戶從鍵盤輸入的數據,也可以用於獲取文件中的數據。Scanner 類在 java.util 包中,因此在使用時需要先 import 該包。
一、Scanner的常用方法
Scanner 的常用方法如下:
Scanner sc = new Scanner(System.in); //獲取鍵盤輸入
Scanner sc = new Scanner(new File("input.txt")); //獲取文件數據
sc.nextInt(); //獲取輸入中的整數值
sc.next(); //獲取輸入中的字元串值
sc.nextDouble(); //獲取輸入中的雙精度浮點值
sc.hasNext(); //判斷輸入中是否還有下一個值
sc.close(); //關閉 Scanner 對象
可以看到,通過 Scanner 的不同方法,可以方便地獲取不同類型的數據。
二、Scanner的用法示例
1. 從鍵盤獲取數據
import java.util.Scanner;
public class ScannerDemo {
public static void main(String[] args) {
//創建Scanner對象,獲取鍵盤輸入
Scanner sc = new Scanner(System.in);
System.out.println("請輸入一個整數:");
int num = sc.nextInt();
System.out.println("輸入的整數值為:" + num);
sc.close();
}
}
運行結果:
請輸入一個整數: 5 輸入的整數值為:5
2. 從文件中獲取數據
首先我們需要準備一個輸入文件 input.txt,文件內容如下:
Tom 80.5 Jerry 90.0
然後,我們就可以通過以下方式從文件中獲取數據:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class ScannerDemo {
public static void main(String[] args) throws IOException {
//創建Scanner對象,從文件中獲取數據
Scanner sc = new Scanner(new File("input.txt"));
while (sc.hasNext()) {
String name = sc.next();
double score = sc.nextDouble();
System.out.println(name + " 的成績為:" + score);
}
sc.close();
}
}
運行結果:
Tom 的成績為:80.5 Jerry 的成績為:90.0
三、小結
本文介紹了 Scanner 的基本使用方法,包括從鍵盤和文件中獲取數據的示例。Scanner 是 Java 中常用的輸入方式之一,在實際開發中應用廣泛。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/197187.html
微信掃一掃
支付寶掃一掃