나는 텍스트 파일 에서 읽은 다음 배열 에 내용을 추가 하려는이 방법을 가지고 있습니다 . 내 방법은 괜찮아 보이지만 화면에 null 이 표시됩니다. 암호.
File text = new File("C:\\Users\\Stephen\\Desktop\\CA2\\src\\Management_System_Package\\GAMES.txt");
Scanner scnr = new Scanner(text);
String GameLine;
GameLine = scnr.nextLine();
while (scnr.hasNextLine()) {
Management_System Game = new Management_System("", "", 0, 0, 0);
int Comma1 = GameLine.indexOf(", ");
String Title = GameLine.substring(0, Comma1).trim();
Game.setTitle(Title);
System.out.print(Title);
int Comma2 = GameLine.indexOf(", ", Comma1 + 1 );
String Genre = GameLine.substring(Comma1 + 1, Comma2);
Game.setGenre(Genre);
int Comma3 = GameLine.indexOf(", ", Comma2 + 1 );
String ID = GameLine.substring(Comma2 + 1, Comma3);
Game.setID(Double.parseDouble(ID));
int Comma4 = GameLine.indexOf(", ", Comma3 + 1 );
String Rating = GameLine.substring(Comma3 + 1, Comma4);
Game.setRating(Integer.parseInt(Rating));
String Quantity = GameLine.substring(Comma4 + 1).trim();
Game.setQuantity(Integer.parseInt(Quantity));
add(Game);
GameLine = in.nextLine();
코드에 루프에서 한 줄을 읽고 항상 파일의 마지막 줄을 건너 뛰는 버그가 있기 때문입니다. 파일에 한 줄만 scnr.hasNextLine()
있으면 false
이고 while 루프는 실행되지 않습니다.
그리고 split()
원하는 문자열과 정수를 얻는 더 좋은 방법 이라고 생각 합니다. 다음과 같은 코드 :
String GameLine;
while (scnr.hasNextLine()) {
GameLine = scnr.nextLine();
Management_System Game = new Management_System("", "", 0, 0, 0);
String[] tags = GameLine.split(",");
Game.setTitle(tags[0]);
Game.setGenre(tags[1]);
Game.setID(Double.parseDouble(tags[2]));
Game.setRating(Integer.parseInt(tags[3]));
Game.setQuantity(Integer.parseInt(tags[4]));
add(Game);
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다