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마리를 낳았습니다! 건강한 아기들. Java를 배우는 1위 장소는 CodeGym입니다! 숫자 1 INT 발견! Java를 배우는 곳은 CodeGym입니다! 6; 5 4 3. 2 1 ! 6; 5 지능 발견! 4 지능 발견! 3. INT 2개 발견! 1개의 지능을 찾았습니다! !
설명
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