Java?Scanner?類讀取一維數(shù)組二維數(shù)組示例詳解
1.概述
(1)Scanner 類是 Java 中一個(gè)用于讀取用戶輸入的工具類。它可以從多種輸入源讀取數(shù)據(jù),例如標(biāo)準(zhǔn)輸入流、文件或字符串。Scanner 類提供了一系列方法來(lái)處理不同數(shù)據(jù)類型的輸入,比如整數(shù)、浮點(diǎn)數(shù)、布爾值、字符和字符串等。
(2)Scanner 類中有兩種比較重要的方法:
以
hasNext開(kāi)頭的方法:用于檢查輸入源中是否還有下一個(gè)標(biāo)記可用,常用的有:hasNext():如果輸入源中還有下一個(gè)標(biāo)記(非空格字符),返回 true。hasNextLine():如果輸入源中還有下一行(非空行),返回 true。hasNextInt():如果輸入源中還有下一個(gè)整數(shù),返回 true。hasNextDouble():如果輸入源中還有下一個(gè)浮點(diǎn)數(shù),返回 true。hasNextBoolean():如果輸入源中還有下一個(gè)布爾值,返回 true。
以
next開(kāi)頭的方法:用于從輸入源中獲取下一個(gè)標(biāo)記并返回相應(yīng)的數(shù)據(jù)類型,常用的有:next():從輸入源中獲取并返回一個(gè)字符串,默認(rèn)以空格為分隔符,以回車 Enter 為結(jié)束符,回車 Enter 后的內(nèi)容則放入緩沖區(qū)。nextLine():從輸入源中獲取并返回一行字符串(以換行符為分隔符)。nextInt():從輸入源中獲取并返回一個(gè)整數(shù)。nextDouble():從輸入源中獲取并返回一個(gè)浮點(diǎn)數(shù)。nextBoolean():從輸入源中獲取并返回一個(gè)布爾值(“true” 或 “false”)。
(3)next() 和 nextLine() 在處理方式和使用場(chǎng)景方面有一些區(qū)別:
next()方法:- 讀取的字符串不包含分隔符,如果輸入中存在多個(gè)以空格分隔的單詞,
next()方法只會(huì)返回第一個(gè)單詞。 - 在讀取之前會(huì)忽略輸入中的前導(dǎo)空格。
- 讀取的字符串不包含分隔符,如果輸入中存在多個(gè)以空格分隔的單詞,
nextLine()方法:- 從輸入源中讀取并返回一整行字符串,包括換行符
\n在內(nèi)。 - 它會(huì)讀取輸入源中的全部?jī)?nèi)容直到遇到換行符,或者輸入結(jié)束。
nextLine()方法返回的字符串可以包含空格和其他特殊字符。
- 從輸入源中讀取并返回一整行字符串,包括換行符
2.使用舉例
2.1.從不同的輸入源讀取數(shù)據(jù)
當(dāng)使用 Scanner 類時(shí),可以從不同的輸入源讀取數(shù)據(jù),包括標(biāo)準(zhǔn)輸入流、文件和字符串等。下面是幾個(gè)使用不同輸入源的示例:
(1)從標(biāo)準(zhǔn)輸入流讀取數(shù)據(jù)
public class Example {
public static void main(String[] args) {
// 創(chuàng)建 Scanner 對(duì)象,使用標(biāo)準(zhǔn)輸入流作為輸入源
Scanner scanner = new Scanner(System.in);
System.out.print("請(qǐng)輸入一個(gè)整數(shù):");
int number = scanner.nextInt(); // 從標(biāo)準(zhǔn)輸入流讀取整數(shù)
System.out.println("你輸入的整數(shù)是:" + number);
scanner.close();
}
}在這個(gè)示例中,我們創(chuàng)建了一個(gè) Scanner 對(duì)象,并將標(biāo)準(zhǔn)輸入流(System.in)作為輸入源。然后我們使用 nextInt() 方法從標(biāo)準(zhǔn)輸入流讀取一個(gè)整數(shù)。
(2)從文件讀取數(shù)據(jù)
public class Example {
public static void main(String[] args) {
try {
// 創(chuàng)建 Scanner 對(duì)象,使用文件作為輸入源
Scanner scanner = new Scanner(new File("input.txt"));
while (scanner.hasNextLine()) {
String line = scanner.nextLine(); // 從文件讀取一行數(shù)據(jù)
System.out.println(line);
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}在這個(gè)示例中,我們創(chuàng)建了一個(gè) Scanner 對(duì)象,并將文件 “input.txt” 作為輸入源。然后我們使用 hasNextLine() 和 nextLine() 方法循環(huán)讀取文件的每一行數(shù)據(jù)并打印出來(lái)。
(3)從字符串讀取數(shù)據(jù)
public class Example {
public static void main(String[] args) {
String input = "Hello World 123";
// 創(chuàng)建 Scanner 對(duì)象,使用字符串作為輸入源
Scanner scanner = new Scanner(input);
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
int number = scanner.nextInt(); // 從字符串讀取整數(shù)
System.out.println("整數(shù):" + number);
} else {
String word = scanner.next(); // 從字符串讀取單詞
System.out.println("單詞:" + word);
}
}
scanner.close();
}
}在這個(gè)示例中,我們創(chuàng)建了一個(gè) Scanner 對(duì)象,并將字符串 “Hello World 123” 作為輸入源。然后我們使用 hasNext()、hasNextInt() 和 next() 方法循環(huán)讀取字符串中的每個(gè)單詞或整數(shù),并打印出來(lái)。
2.2.next() 和 nextLine() 的區(qū)別
class Solution {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// next() && nextLine()
System.out.println("請(qǐng)輸入一個(gè)字符串 nextLine():");
String str1 = scanner.nextLine();
System.out.println(str1);
System.out.println("請(qǐng)輸入一個(gè)字符串 next():");
String str2 = scanner.next();
System.out.println(str2);
}
}結(jié)果如下:
請(qǐng)輸入一個(gè)字符串 nextLine():
Hello World
nextLine() 的讀取結(jié)果為:
Hello World請(qǐng)輸入一個(gè)字符串 next():
Hello World
next() 的讀取結(jié)果為:
Hello
2.3.讀取大小已知的一維數(shù)組
描述:第一行輸入是以一個(gè)整數(shù) n,表示數(shù)組 nums 的長(zhǎng)度,第 2 行輸入 n 個(gè)整數(shù),整數(shù)之間用空格分隔。請(qǐng)將這些整數(shù)保存到數(shù)組 nums 中,然后將其打印出來(lái)。例如:
7
4 9 0 -1 6 8 9
(1)使用 nextInt() 逐個(gè)讀?。?/p>
class Solution {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
//數(shù)組的長(zhǎng)度
int n = scanner.nextInt();
int[] nums = new int[n];
//數(shù)組中的 n 個(gè)數(shù)
for (int i = 0; i < n; i++) {
nums[i] = scanner.nextInt();
}
System.out.println("數(shù)組 nums 的元素為:");
for (int num : nums) {
System.out.print(num + " ");
}
scanner.close();
}
}結(jié)果如下:
7
4 9 0 -1 6 8 9
數(shù)組 nums 的元素為:
4 9 0 -1 6 8 9
(2)使用 nextLine() 先全部讀取,然后逐個(gè)解讀:
class Solution {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
//清除緩沖區(qū)中的換行符
scanner.nextLine();
int[] nums = new int[n];
String input = scanner.nextLine();
//以一個(gè)或者多個(gè)空格為分隔符
String[] numStrings = input.split("\\s+");
for (int i = 0; i < n; i++) {
nums[i] = Integer.parseInt(numStrings[i]);
}
System.out.println("數(shù)組 nums 的元素為:");
for (int num : nums) {
System.out.print(num + " ");
}
scanner.close();
}
}注意事項(xiàng):
- 需要注意的是在使用
nextInt()方法讀取整數(shù)后,緩沖區(qū)仍然會(huì)包含一個(gè)換行符\n。這是因?yàn)?nbsp;nextInt()只讀取了整數(shù)部分,而沒(méi)有讀取換行符。當(dāng)接下來(lái)調(diào)用nextLine()方法時(shí),它會(huì)讀取緩沖區(qū)中的剩余部分,即僅包含換行符的部分。因此,為了確保nextLine()方法可以讀取到用戶輸入的整行字符串,我們需要在調(diào)用nextLine()方法之前清除緩沖區(qū)中的換行符。 - 通過(guò)調(diào)用
scanner.nextLine()但不將其結(jié)果保存到變量中,實(shí)際上是表示我們只想要從緩沖區(qū)中讀取并丟棄這個(gè)換行符。這樣,接下來(lái)調(diào)用nextLine()方法時(shí),它將讀取到用戶輸入行的內(nèi)容,并將其保存到字符串input中,而不會(huì)被之前的換行符干擾。確保清除緩沖區(qū)中的換行符是一種常見(jiàn)的做法,以避免由于換行符殘留而導(dǎo)致不正確的輸入或跳過(guò)輸入的情況發(fā)生。
如果在上面代碼中沒(méi)有 scanner.nextLine() 這行語(yǔ)句的話,那么會(huì)出現(xiàn)如下錯(cuò)誤:
7
Exception in thread "main" java.lang.NumberFormatException: For input string: ""at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:592)
at java.lang.Integer.parseInt(Integer.java:615)
at Solution.main(Solution.java:15)
2.4.讀取大小未知的一維數(shù)組
描述:輸入若干個(gè)整數(shù),整數(shù)之間用空格分隔。請(qǐng)將這些整數(shù)保存到數(shù)組 nums 中,然后將其打印出來(lái)。例如:
1 12 3 4 5 6
(1)使用 nextInt() 逐個(gè)讀?。?/p>
class Solution {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
List<Integer> nums = new ArrayList<>();
while (scanner.hasNextInt()) {
nums.add(scanner.nextInt());
}
System.out.println("數(shù)組 nums 的元素為:");
for (int num : nums) {
System.out.print(num + " ");
}
scanner.close();
}
}注意事項(xiàng):
- 如果在控制臺(tái)手動(dòng)輸入若干個(gè)整數(shù),期望手動(dòng)停止輸入后,程序結(jié)束讀取整數(shù),可以使用其他方式來(lái)指示結(jié)束輸入的條件。一種常見(jiàn)的方式是通過(guò)輸入特定的字符或字符串來(lái)表示結(jié)束;
- 由于是逐個(gè)讀取,因此事先不知道數(shù)組的長(zhǎng)度,所以上面代碼中使用 list 來(lái)存儲(chǔ);
(2)使用 nextLine() 先全部讀取,然后逐個(gè)解讀:
class Solution {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
input = input.trim();
String[] numStrings = input.split("\\s+");
int[] nums = new int[numStrings.length];
for (int i = 0; i < numStrings.length; i++) {
nums[i] = Integer.parseInt(numStrings[i]);
}
System.out.println("\n數(shù)組 nums 的元素為:");
for (int num : nums) {
System.out.print(num + " ");
}
scanner.close();
}
}結(jié)果如下:
1 12 3 4 5 6
數(shù)組 nums 的元素為:
1 12 3 4 5 6
2.5.讀取長(zhǎng)度大小已知的二維數(shù)組
描述:第一行輸入是兩個(gè)整數(shù) m 和 n,中間用空格分隔,后面跟隨 m 行,每行都有 n 個(gè)整數(shù),整數(shù)之間用空格分隔。例如:
3 4
1 8 7 3
2 3 4 5
4 5 6 7
(1)使用 next() 讀取:
class Solution {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 讀取整數(shù) m 作為二維數(shù)組的長(zhǎng)度
int m = scanner.nextInt();
int n = scanner.nextInt();
scanner.nextLine(); // 讀取換行符
//創(chuàng)建二維數(shù)組 nums
int[][] nums = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
nums[i][j] = scanner.nextInt();
}
}
//打印二維數(shù)組 nums
System.out.println("\n數(shù)組 nums 的元素為:");
for (int i = 0; i < m; i++) {
for (int j = 0; j < nums[i].length; j++) {
System.out.print(nums[i][j] + " ");
}
System.out.println();
}
}
}(2)使用 nextLine() 讀?。?/p>
class Solution {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 讀取整數(shù) m 作為二維數(shù)組的長(zhǎng)度
int m = scanner.nextInt();
int n = scanner.nextInt();
scanner.nextLine(); // 讀取換行符
//創(chuàng)建二維數(shù)組 nums
int[][] nums = new int[m][n];
//讀取 m 行數(shù)據(jù)到二維數(shù)組 nums
for (int i = 0; i < m; i++) {
//讀取整行數(shù)據(jù)
String line = scanner.nextLine();
//將每個(gè)整數(shù)分割保存到一維數(shù)組
String[] values = line.split("\\s+");
//創(chuàng)建長(zhǎng)度為 n 的一維數(shù)組
nums[i] = new int[n];
//保存每個(gè)整數(shù)到一維數(shù)組
for (int j = 0; j < n; j++) {
nums[i][j] = Integer.parseInt(values[j]);
}
}
//打印二維數(shù)組 nums
System.out.println("\n數(shù)組 nums 的元素為:");
for (int i = 0; i < m; i++) {
for (int j = 0; j < nums[i].length; j++) {
System.out.print(nums[i][j] + " ");
}
System.out.println();
}
}
}結(jié)果如下:
3 4
1 8 7 3
2 3 4 5
4 5 6 7數(shù)組 nums 的元素為:
1 8 7 3
2 3 4 5
4 5 6 7
2.6.讀取長(zhǎng)度大小未知的二維鋸齒數(shù)組
描述:輸入若干行,每一行有若干個(gè)整數(shù),整數(shù)之間用空格分隔,并且每一行的整數(shù)個(gè)數(shù)不一定相同。例如:
1 2 3 45
3 4
9 0 -1 2
1 4 6
4 6 7 8 7
class Solution {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
List<List<Integer>> nums = new ArrayList<>();
// 逐行讀取數(shù)據(jù)并保存到二維數(shù)組鋸齒 nums
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line.isEmpty()) {
break; // 輸入結(jié)束
}
String[] values = line.split("\\s+");
List<Integer> row = new ArrayList<>();
for (String value : values) {
row.add(Integer.parseInt(value));
}
nums.add(row);
}
//打印二維鋸齒數(shù)組 nums
System.out.println("二維鋸齒數(shù)組 nums 的元素為:");
for (List<Integer> row : nums) {
for (Integer value : row) {
System.out.print(value + " ");
}
System.out.println();
}
}
}結(jié)果如下:
1 2 3 45
3 4
9 0 -1 2
1 4 6
4 6 7 8 7二維鋸齒數(shù)組 nums 的元素為:
1 2 3 45
3 4
9 0 -1 2
1 4 6
4 6 7 8 7
以上就是Java Scanner 類讀取一維數(shù)組二維數(shù)組示例詳解的詳細(xì)內(nèi)容,更多關(guān)于Java Scanner讀取數(shù)組的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Springmvc模式上傳和下載與enctype對(duì)比
這篇文章主要介紹了Springmvc模式上傳和下載與enctype對(duì)比,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-12-12
Java Spring分別實(shí)現(xiàn)定時(shí)任務(wù)方法
這篇文章主要為大家詳細(xì)介紹了Java與Spring設(shè)置動(dòng)態(tài)定時(shí)任務(wù)的方法,定時(shí)任務(wù)的應(yīng)用場(chǎng)景十分廣泛,如定時(shí)清理文件、定時(shí)生成報(bào)表、定時(shí)數(shù)據(jù)同步備份等2022-07-07
IDEA安裝后找不到.vmoptions文件的問(wèn)題及解決
這篇文章主要介紹了IDEA安裝后找不到.vmoptions文件的問(wèn)題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-04-04
Java通過(guò)MyBatis框架對(duì)MySQL數(shù)據(jù)進(jìn)行增刪查改的基本方法
MyBatis框架由Java的JDBC API進(jìn)一步封裝而來(lái),在操作數(shù)據(jù)庫(kù)方面效果拔群,接下來(lái)我們就一起來(lái)看看Java通過(guò)MyBatis框架對(duì)MySQL數(shù)據(jù)進(jìn)行增刪查改的基本方法:2016-06-06

