gpt4 book ai didi

仅使用一个扫描仪的 java.util.NoSuchElementException

转载 作者:行者123 更新时间:2023-12-01 16:52:43 26 4
gpt4 key购买 nike

因此,我尝试使用扫描仪读取 .csv 文件的内容,每次收到标题所示的错误时。

首先,我读到了 Internet这是因为您的项目中不能有多个 Scanner 实例,因为它们会消耗输入,因此我使用 BufferedReader 扫描用户选择,并使用 Scanner 打开 .csv 文件。

现在我再次收到错误,只有一个扫描仪实例,我不知道为什么会发生这种情况。

问题.java

import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
import java.util.ArrayList;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Question {
public static void menu() {
System.out.println("\nEnter your choice :\n");
System.out.println("1 - Load Hotels and Reservations from file");
System.out.println("\nEnter \"1\"");
int choice = 1;
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(System.in));
choice = Integer.parseInt(br.readLine());
} catch (IOException ioe) {
ioe.printStackTrace();
}
if (choice == 1)
loadOption();
}

public static void loadOption() {
Scanner scan;
ArrayList<Hotel> hotel = new ArrayList();
try {
Hotel hotel = new Hotel();
scan = new Scanner(new File("data1.csv"));
scan.useDelimiter(";");
int column = 1;
while (scan.hasNext()) {
scan.next();
if (column == 1)
hotel.id = scan.next();
if (column == 2)
hotel.name = scan.next();
if (column == 3)
hotel.star = scan.next();
if (column == 4)
hotel.rooms = scan.next();
}
System.out.print("Files Succesfully Loaded!!!\n");
scan.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}

public static void main(String[] args) {
Question obj = new Question();
obj.menu();
}

};

酒店.java

public class Hotel extends Question {
String id, star, rooms, name;

public Hotel() {
} // constructor
};

这就是我编译它们的方式:

javac Hotel.java
javac Question.java
java Question

确切的错误是这样的:

Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at Question.loadOption(Question.java:43)
at Question.menu(Question.java:27)
at Question.main(Question.java:62)

最佳答案

您检查hasNext(),但随后调用next()两次。所以第二个调用未被选中。更糟糕的是,第一次调用是不需要的并且没有效果。您也不要增加 column 变量。

试试这个:

Hotel hotel = new Hotel();
scan = new Scanner(new File("data1.csv"));
scan.useDelimiter(";");
int column=1;
while (scan.hasNext()) {
//scan.next(); this is not needed
if (column == 1)
hotel.id = scan.next();
if (column == 2)
hotel.name = scan.next();
if (column == 3)
hotel.star = scan.next();
if (column == 4)
hotel.rooms = scan.next();
//this is needed as well:
column++;
}
System.out.print("Files Succesfully Loaded!!!\n");
scan.close();

注意:您仍然只创建一个 Hotel 实例。

关于仅使用一个扫描仪的 java.util.NoSuchElementException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36746327/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com