[英]Java Double Array
我在使用包含浮点数2.1和4.3的文本文件将值设置和放置到数组中时遇到麻烦,每个数字都用空格分隔-以下是我得到的错误:
线程“main”java.util.NoSuchElementException中的异常
import java.util.*;
import java.io.*;
public class DoubleArray {
public static void main(String[] args) throws FileNotFoundException {
Scanner in = new Scanner(new FileReader("mytestnumbers.txt"));
double [] nums = new double[2];
for (int counter=0; counter < 2; counter++) {
int index = 0;
index++;
nums[index] = in.nextDouble();
}
}
}
谢谢,我确定这不是一个很难回答的问题...感谢您的宝贵时间。
我建议你在使用它之前立即打印index
的值; 您应该很快发现问题。
看来您没有从文件中获得好的价值。
Oli也是正确的,你的索引有问题,但我会尝试这个来验证你从你的文件中得到双打:
String s = in.next();
System.out.println("Got token '" + s + "'"); // is this a double??
double d = Double.parseDouble(s);
编辑:我把这部分归还......
您根本没有令牌可获取。 以下是给出异常的下一个双重内容:
InputMismatchException - if the next token does not match the Float
regular expression, or is out of range
NoSuchElementException - if the input is exhausted
IllegalStateException - if this scanner is closed
在调用next *()方法之前,应始终使用hasNext *()方法
for (int counter=0; counter < 2; counter++) {
if(in.hasNextDouble(){
nums[1] = in.nextDouble();
}
}
但我认为您没有做对,我宁愿
for (int counter=0; counter < 2; counter++) {
if(in.hasNextDouble(){
nums[counter] = in.nextDouble();
}
}
nextDouble
方法抛出NoSuchElementException
@see javadoc
我不明白您要在循环中尝试做什么?
for (int counter=0; counter < 2; counter++) {
int index = 0;
index++; <--------
nums[index] = in.nextDouble();
}
您在声明index = 0,然后将其递增到1,然后再使用它。
你为什么不写int index = 1; 直接?
因为每次循环运行时它都被声明为零,然后将值更改为1.要么将它声明为循环。
每次循环执行一次迭代时,它都声明变量index,然后使用index++
增加index。 代替使用索引,而使用counter,如下所示: num [counter] = in.nextDouble()
。
您应该在for循环之外初始化index
。
int index = 0;
for (int counter=0; counter < 2; counter++)
{
index++;
nums[index] = in.nextDouble();
}
您的索引在for循环的每次迭代开始时都设置为零。
编辑:您还需要检查以确保您仍然有输入。
int index = 0;
for (int counter=0; counter < 2; counter++)
{
if(!in.hasNextDouble())
break;
index++;
nums[index] = in.nextDouble();
}
检查mytestnumbers.txt文件,确保您尝试扫描的数据格式正确。 你得到的例外暗示它不是。
请记住, in.nextDouble()
将搜索由空格分隔的双数字。 换句话说,“4.63.7”不等于“4.6 3.7” - 空间是必需的。 (我不记得了,但我相信nextDouble()
只会搜索包含小数点的数字,因此我不认为“ 4”等于“ 4.0”。如果要查找小数,数字,那么您的文件中应该有十进制数字。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.