Reputation: 157
I want to read double values stored in a text file and store those values in an array.The input file has one value in each line. Following is my code.
File file=new File("val.txt");
List<Double> value = new ArrayList<Double>();
Scanner input = new Scanner(file);
while(input.hasNext()){
value.add(scanner.nextDouble());}
But i get Nosuchelement exception. What is wrong the code?. How to read double values from the file and store it?
Upvotes: 0
Views: 267
Reputation: 93842
It seems like you are using 2 scanners. You're checking with one if it has a value and you're trying to add this value using another scanner.
Use only the input
one.
So change it to:
File file=new File("val.txt");
List<Double> value = new ArrayList<Double>();
Scanner input = new Scanner(file);
while(input.hasNextDouble()){
value.add(input.nextDouble());
}
Note that the Scanner
use your default locale (if you don't specify one). So if this locale separates decimals by a ,
you'll add nothing to your List
. So make sure you use one that separates decimals by a dot.
Scanner input = new Scanner(file).useLocale(Locale.UK);
Upvotes: 3