Java-从文件中读取有符号整数
我试图从一个文件中读入10个有符号整数到一个数组中,但由于某种原因,这并没有发生,而且在编译和运行时我也没有收到任何错误。我只想用另一双眼睛看看这件事,看看我可能遗漏了什么 测试文件是“input.txt”,包含:-1、4、32、0、-12、2、30、1、-3、-32 这是我的密码:Java-从文件中读取有符号整数,java,arrays,java.util.scanner,readfile,Java,Arrays,Java.util.scanner,Readfile,我试图从一个文件中读入10个有符号整数到一个数组中,但由于某种原因,这并没有发生,而且在编译和运行时我也没有收到任何错误。我只想用另一双眼睛看看这件事,看看我可能遗漏了什么 测试文件是“input.txt”,包含:-1、4、32、0、-12、2、30、1、-3、-32 这是我的密码: public void readFromFile(String filename) { try { File f = new File(filename); Sca
public void readFromFile(String filename)
{
try {
File f = new File(filename);
Scanner scan = new Scanner(f);
String nextLine;
int[] testAry = new int[10];
int i = 0;
while (scan.hasNextInt())
{
testAry[i] = scan.nextInt();
i++;
}
}
catch (FileNotFoundException fnf)
{
System.out.println(fnf.getMessage());
}
}
您可能正在抛出另一个未捕获的异常 () 从输入扫描的int抛出:
InputMismatchException - if the next token does not match the Integer regular expression, or is out of range
NoSuchElementException - if input is exhausted
IllegalStateException - if this scanner is closed
或者,你可以去老派学校,用一个缓冲读取器来验证你是否得到了数据
try{
FileInputStream fstream = new FileInputStream(filename);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
System.out.println (strLine);
}
in.close();
}catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
您可以在扫描仪对象上使用默认分隔符 尝试使用我在useDelimiter(\\s*,\\s*)”行中得到的分隔符。它的正则表达式用逗号分隔文件中的输入
try {
File f = new File("input.txt");
Scanner scan = new Scanner(f);
scan.useDelimiter("\\s*,\\s*");
String nextLine; //left it in even tho you are not using it
int[] testAry = new int[10];
int i = 0;
while (scan.hasNextInt()) {
testAry[i] = scan.nextInt();
System.out.println(testAry[i]);
i++;
}
} catch (FileNotFoundException fnf) {
System.out.println(fnf.getMessage());
}
这是整个程序吗?对我来说很好…testAry是一个局部变量,你不返回它,那么这个方法到底做什么呢?只需将输入读入数组,我需要在程序的其他一些函数中使用该数组。在调试模式下,它会第一次点击while语句并跳过这是一个本地数组,我看不到您将该信息保存在函数非本地的任何地方,如果这些是逗号,您需要更改扫描程序使用的分隔符。如果读入,这是我试图在文件后运行的代码行:
int[]inputArray=new int[10];inputArray=hmwk.readFromFile(“input.txt”);hmwk.algorithmOne(inputArray);
但是inputArray在哪里填充?另外,如果hasNextInt()循环没有运行,因为23不是整数,因为逗号,请更改分隔符以修复该问题。