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
GO TO FULL VERSION