java scanner 오류
276
작성한 질문수 1
txt파일에는 아래와 같이 저장되어 있습니다. 점수가 가장 높은 학생의 이름을 출력해야하고 점수가 동일할 경우 모두 출력하는 프로그램입니다.
김일번 64
김이번 83
김삼번 26
김사번 36
김오번 78
김육번 54
김칠번 60
김팔번 85
김구번 45
김십번 85
프로그램을 실행했을 때
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:947)
at java.base/java.util.Scanner.next(Scanner.java:1602)
at java.base/java.util.Scanner.nextInt(Scanner.java:2267)
at java.base/java.util.Scanner.nextInt(Scanner.java:2221)
이렇게 오류가 발생합니다. 해결방법 아시는 분 가르쳐주세요!!ㅜㅜ
package kh;
import java.io.*;
import java.util.Scanner;
class Student
{
//int id;
String name;
int grade;
Student(String name, int grade)
{
//this.id=id;
this.name=name;
this.grade=grade;
}
}
class StudentTable{
Student[] st;
StudentTable(int size)
{
st=new Student[size];
}
void maxStudent()
{
int maxGrade=0;
for(Student student : st)
{
if(student.grade > maxGrade)
{
maxGrade = student.grade;
}
}
System.out.println("최고 점수를 가진 학생:");
for(Student student : st)
{
if(student.grade == maxGrade)
{
System.out.println(" " + student.name + " " + student.grade);
}
}
}
}
public class homework05{
public static void main(String[] args) {
StudentTable stable;
try {
FileInputStream fin=new FileInputStream("C:\\Users\\user\\Desktop\\student_score.txt");
Scanner scanner = new Scanner(fin);
int size=scanner.nextInt();
stable=new StudentTable(size);
for(int i=0; i<stable.st.length; i++)
{
//int id=scanner.nextInt();
String name=scanner.next();
int grade=scanner.nextInt();
stable.st[i]=new Student(name,grade);
System.out.println(" "+name+" "+grade);
}
scanner.close();
stable.maxStudent();
}
catch(FileNotFoundException e)
{
System.out.println("file not exist");
}
}
}
답변 1
0
안녕하세요, 인프런 AI 인턴입니다.
dkfma0799님, 제시하신 코드와 오류 메시지를 보면 java.util.InputMismatchException 예외는 Scanner가 예상과 다른 타입의 데이터를 만났을 때 발생합니다. 코드 상에서 Scanner는 파일의 첫 줄에서 정수를 읽으려고 시도합니다(int size=scanner.nextInt();). 그러나 txt파일의 내용을 보면 파일의 시작이 정수가 아닌 문자열(이름)로 시작합니다. 이것이 예외의 원인입니다.
txt 파일의 첫 줄에 학생의 총 수를 읽으려고 하지만, 실제 파일에는 이름과 점수가 차례로 나열되어 있습니다. 프로그램이 파일의 첫 번째 문자열(이름)을 정수로 해석하려고 시도할 때 InputMismatchException이 발생합니다.
이 문제를 해결하기 위한 한 가지 방법은 파일에서 직접 학생의 수를 읽는 대신, 학생의 목록을 읽어내는 동안 동적으로 ArrayList와 같은 가변 크기 컬렉션을 사용하는 것입니다. 이렇게 하면 미리 학생의 수를 알 필요가 없어집니다.
아래는 수정된 코드의 일부입니다. 가변 크기의 ArrayList를 사용하여 학생들을 저장하고 관리하는 방법을 보여줍니다:
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
class StudentTable{
ArrayList<Student> st = new ArrayList<>();
void maxStudent() {
int maxGrade = 0;
for(Student student : st) {
if(student.grade > maxGrade) {
maxGrade = student.grade;
}
}
System.out.println("최고 점수를 가진 학생:");
for(Student student : st) {
if(student.grade == maxGrade) {
System.out.println(" " + student.name + " " + student.grade);
}
}
}
}
public class homework05 {
public static void main(String[] args) {
StudentTable stable = new StudentTable();
try {
FileInputStream fin = new FileInputStream("C:\\Users\\user\\Desktop\\student_score.txt");
Scanner scanner = new Scanner(fin);
while (scanner.hasNext()) {
String name = scanner.next();
int grade = scanner.nextInt();
stable.st.add(new Student(name, grade));
}
scanner.close();
stable.maxStudent();
} catch (FileNotFoundException e) {
System.out.println("file not exist");
}
}
}
이 방법을 사용하면 파일의 첫 줄에 학생 수를 명시할 필요가 없으며, 파일을 끝까지 읽으면서 학생 정보를 동적으로 ArrayList에 추가할 수 있습니다.
Jib 이미지 빌드에서 docker credential 관련으로 이슈가 있다면
1
18
1
리뉴얼 시기
0
4
0
스크립트에 대해 질문 있습니다.
1
13
1
같은 사용자가 연속된 중복 호출할 경우 어떻게 되는지 궁금합니다!
1
12
1
조건 검색 질문
0
12
1
JPA 엔티티로 만들었다고 기술종속이 아닌지에 대한 질문
0
16
2
클로드코드 명령어-대화&세션관리 수업 자료
0
30
1
정처기 필기 준비할때 이 이론을 다시 외워도 될까요?
0
42
2
PlatformTransactionManager, ResourcelessTransactionManager 질문
1
50
2
자료 한번에 다운받기
0
26
1
스프링 빈 등록 방법 2가지 다 알아야하는 이유
0
48
1
mybatis 를 이용한 crud에서 insert에서 resultType='long" 이라고 하셨는데요,
0
24
1
댓글 삭제 로직에서 동시성 문제 발생 가능성
0
34
1
설계 트레이드 오프 링크 접속 안됨
0
69
2
테스트 질문, 어떤것을 사용할것인것에 대해서
0
38
1
Shape 클래스 실습 코드 피드백 요청드립니다
0
37
2
재고 감소와 쿠폰 발급은 왜 서로 다른 방식으로 동시성을 제어하나요?
0
44
2
깃허브주소 궁금합니다.
0
31
2
mariaDB 설정
0
28
1
섹션4 퀴즈 오타있어요.
0
41
1
AWS 배포 성능테스트
0
65
2
조건 반복문 질문: for 문 ?
0
58
1
run() 메서드 안에 지역변수 sum을 사용한 이유
0
76
1
7강 보고 있는데요.. 글자가 너무 작아요
0
35
1





