简体   繁体   中英

reading data from a file into array

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;

public class question2_Arrays {


public static void main(String[] args) throws FileNotFoundException{

    double[]loanbalanceArray = new double[500];
    int index = 0;

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

    while(inputFile.hasNext()&& index<loanbalanceArray.length){
        loanbalanceArray[index] = inputFile.nextInt();
        index ++;
        }
    inputFile.close();

I am trying to read the contents of the text file loanbalance into an array sized 500 this is what i have so far but when i execute the program it gives me this error "Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Unknown Source) at java.util.Scanner.next(Unknown Source) at java.util.Scanner.nextInt(Unknown Source)"

any suggestions where i could be going wrong?

while (inputFile.hasNextDouble() || index<loanbalanceArray.length){
    loanbalanceArray[index] = inputFile.nextDouble();
    index ++;
    }

Use inputFile.hasNextInt method. Your input can return true on hasNext call but it can be not int or null and throw exception during call of loanbalanceArray[index] = inputFile.nextDouble();

And according to your comments you're using loanbalanceArray[index] = inputFile.hasNextDouble() for assignment, but you should use loanbalanceArray[index] = inputFile.nextDouble()

hasNextDouble() checking if your input has double value further and returns Boolean is so but nextDouble() returns actual next Double value of input

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM