gpt4 book ai didi

java - java 代码中的InputMismatchException 错误。请给一些建议

转载 作者:行者123 更新时间:2023-12-02 09:24:01 25 4
gpt4 key购买 nike

出于某种原因,我在第 44 行不断收到 inputmistmatch 异常 (int fileAge = inputFile.nextInt();)

我尝试隔离该部分代码并将其与手动创建的文件一起使用,但它仍然给出相同的错误。我尝试使用不同的分隔符而不是分号。我尝试删除年龄变量,而是重新编写代码,这样它只从性别开始询问,但随后我开始收到“无此类元素”的异常。不确定问题是什么。

public static void main(String[]args) {
Scanner kb = new Scanner (System.in);
int age;
String gender;
String email;
int salary;
int end;
int maleCount = 0;
int femaleCount = 0;

do {
System.out.println("Please enter age");
age = kb.nextInt();
age = validateAge(age);
System.out.println("Please enter gender. male or female: ");
gender = kb.next();
System.out.println("Please enter email");
email = kb.next();
System.out.println("Please enter annual salary");
salary = kb.nextInt();
salary = validateSalary(salary);
try {
FileWriter fw = new FileWriter("salaries.txt", true);
PrintWriter outputFile = new PrintWriter(fw);
outputFile.println(age + ";" + gender + ";" + email + ";" + salary);
outputFile.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Add another person or end here? Enter 1 to end or 2 to continue: ");
end = kb.nextInt();
}while (end != 1);

Scanner inputFile = new Scanner("salaries.txt").useDelimiter(";");
while(inputFile.hasNext()) {
int fileAge = inputFile.nextInt(); //i get the error here
String fileGender = inputFile.next();
String fileEmail = inputFile.next();
int fileSalary = inputFile.nextInt();
if(fileGender.equals("male")) {
maleCount ++;
}else {
femaleCount ++;
}
}

最佳答案

我可以直接看到的问题之一是:

 Scanner inputFile = new Scanner("salaries.txt").useDelimiter(";");

scanner 类的构造函数接受 java.io.File 类的引用,而不是要读取的文件的字符串名称。

所以,理想情况下您的代码应该是

       File file = new File("salaries.txt");
Scanner inputFile = new Scanner(file);

此外,我之前尝试过读取 csv 文件,您也可以引用以下代码片段来读取分号分隔的文件。

        File file = new File("salaries.txt");
System.out.println(file.getAbsolutePath());
while (inputFile.hasNextLine()) {
String line = inputFile.nextLine();
String[] lineArray = line.split(";");
int fileAge = Integer.parseInt(lineArray[0]);
String fileGender = lineArray[1];
String fileEmail = lineArray[2];
int fileSalary = Integer.parseInt(lineArray[3]);
if (fileGender.equals("male")) {
maleCount++;
} else {
femaleCount++;
}
}
System.out.println(maleCount);

希望对您有所帮助。

关于java - java 代码中的InputMismatchException 错误。请给一些建议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58470126/

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