Java 中的 nextInt() 方法是什麼?
示例 1
讓我們首先深入了解基本示例。import java.util.Scanner;
public class TestIntInput {
public static void checkInt(String testData) {
System.out.println(testData);
Scanner scanner = new Scanner(testData);
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
// calling the nextInt() method
System.out.println(scanner.nextInt() + "\t\t INT FOUND!");
} else {
System.out.println(scanner.next() + "\t\t");
}
}
scanner.close();
System.out.println();
}
public static void main(String[] args) {
String testData1 = "My 3 years old cat Diana, just gave birth to 5 healthy babies.";
String testData2 = "The number 1 place to learn Java is CodeGym!";
String testData3 = "6; 5 4 3. 2 1 !";
checkInt(testData1);
checkInt(testData2);
checkInt(testData3);
}
}
輸出
我 3 歲的貓黛安娜 (Diana) 剛生下 5 個健康的寶寶。我的 3 INT 找到了!歲的貓黛安娜,剛剛生下 5 INT FOUND!健康的嬰兒。學習 Java 的第一名是 CodeGym!找到 1 號 INT!學習 Java 的地方是 CodeGym!6; 5 4 3. 2 1 !6; 5 INT 找到了!4 INT 找到了!3. 找到 2 個 INT!找到 1 個 INT!!
解釋
在testData3的上述示例中需要注意的一件事是,數字需要以空格分隔才能作為單個 int 進行掃描。這就是為什麼 6 和 3 沒有被識別為整數的原因,因為它們分別以冒號和逗號分隔。示例 2
此示例使用系統輸入將其掃描為整數。import java.util.Scanner;
public class TestSystemInput {
public static void getFinalExamScore() {
System.out.println("Get Your Final Exam Score!\n");
int finalScore = 0;
int totalCourses = 0;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter total Courses: ");
totalCourses = scanner.nextInt();
for (int i = 0; i < totalCourses; i++) {
System.out.println("Enter score in course " + (i + 1) + " : ");
finalScore = finalScore + scanner.nextInt();
}
System.out.println("Your final Score = " + finalScore);
scanner.close();
}
public static void main(String[] args) {
getFinalExamScore();
}
}
輸出
獲取您的期末考試成績!輸入總課程數:3 輸入課程 1 的分數:10 輸入課程 2 的分數:15 輸入課程 3 的分數:15 您的最終分數 = 40