gpt4 book ai didi

java - 初级 Java 程序员的挣扎(未找到行)

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

目标是询问每个州的国会大厦是什么,说明正确或错误,然后在最后给出正确答案的总数。编译时它没有给我任何错误,但是当我尝试运行它时它说:java.uitl.NoSuchElementException:未找到行(在 java.util.Scanner 中)

可能还有更多错误,但我宁愿先关注这个错误。如有任何反馈,我们将不胜感激,谢谢!

代码:

 import java.util.*;
import java.io.*;
public class States
{
public static void main(String[] args)
throws java.io.IOException
{
Scanner inputt = new Scanner (System.in);
String[][] cs = new String [50][1];
while (true)
{
String in = " ";
boolean ans = false;
int tally = 0;
int count = 0;
load(cs);
in = input(count, cs);
ans = check(in, count, cs);
if (ans == true)
{
tally ++;
continue;
}
count= count +2;
if (count > 100)
{
System.out.println("The count of correct answers is " + tally + ".");
break;
}
}//end main method while loop
}//end main method
public static void load(String[][] cs)
throws java.io.IOException
{
String filName = " ";
filName = "C://Users/Troy/Documents/Class Documents/CSC 225/StateCapitals.txt";
Scanner inputt = new Scanner(new File(filName));
for (int row = 0; row < cs.length; row ++)
{
for (int col = 0; col < cs[row].length; col ++)
{
cs[row][col] = inputt.nextLine();
}
}//end for loop
inputt.close();
}//end load method
public static String input(int count, String[][] cs)
{
Scanner inputt = new Scanner (System.in);
System.out.print("What is the capital of " + cs[count][0] + "? -");
String t = inputt.nextLine().trim().toUpperCase();
return t;
}//end input method
public static Boolean check(String in, int count, String [][] cs)
{
boolean correct = false;
if (cs[count +1][0].compareTo(in)==0)
{
correct=true;
System.out.println("Your answer is correct.");
}
else
{
System.out.println("The correct answer should be " + cs[count + 1][0]);
}
return correct;
}//end check method
}//end class

最佳答案

您没有在加载方法的开头使用扫描器类正确读取文件。

尝试使用这样的东西

ArrayList<String> lines = new ArrayList<>();

JOptionPane.showMessageDialog(null, "Please choose a file");
JFileChooser input = new JFileChooser();
int a = input.showOpenDialog(null);
String file = "";

if (a == JFileChooser.APPROVE_OPTION) {
File selectedFile = input.getSelectedFile();
file = selectedFile.getPath();
}

//use file input to read in line one at a time
FileInputStream fstream = new FileInputStream(file);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = br.readLine()) != null) {
lines.add(line);
}

或者,如果您想使用 Scanner 类,您可以使用类似的东西

// Location of file to read
File file = new File("data.txt");

try {
Scanner scanner = new Scanner(file);

while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
scanner.close();
}

catch (FileNotFoundException e) {
e.printStackTrace();
}

关于java - 初级 Java 程序员的挣扎(未找到行),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27215707/

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