arrays - Getting a no such element exception dont know why -


i need create 2 arrays file has 3 columns of data. have made far.

import java.util.*; import java.io.*; import java.util.arrays;  public class readfile {  public static void main(string[] args) throws filenotfoundexception {  scanner infile=null;  try  {    infile = new scanner (new file("data.txt"));;  }  catch (filenotfoundexception e)      {         system.out.println ("file not found!");         // stop program if no file found         system.exit (0);     }  int count=0;  int[] year = new int[40];  int[] temperature = new int[40];  infile.nextint();  while (infile.hasnextint()) {      year[count] = infile.nextint();    temperature[count] = infile.nextint();    infile.nextint();    count++; }   system.out.println(arrays.tostring(year)); system.out.println(arrays.tostring(temperature)); } } 

the data file looks this. 1 1950 11

2  1950  22  3  1950  65  4  1950  103  5  1950  99  6  1950  54  7  1950  109  8  1950  85  9  1950  72  10  1950  120  11  1951  26  12  1951  35  13  1951  59  14  1951  110  15  1951 103  16  1951  49  17  1951  99  18  1951  91  19  1951  85  20  1951  117  21  1953  26  22  1953  41  23  1953  69  24  1953  110  25  1953  100  26  1953  72  27  1953  87  28  1953  102  29  1953  95  30  1953  102  31  1954  33  32  1954  46  33  1954  57  34  1954  106  35  1954  119  36  1954  93  37  1954  57  38  1954  89  39  1954  88  40  1954  92 

the file makes 100% sense me , sounds should work, im getting strange exception. can me out?

you call infile.hasnextint() every 3 calls infile.nextint(). whereas last call doesn't have next integer because @ end of file (after 92 in 40 1954 92 has been read).

you can shift index 1 around i.e.:

 int[] year = new int[40];  int[] temperature = new int[40];  while (infile.hasnextint()) {     infile.nextint(); //the throw away value    year[count] = infile.nextint();    temperature[count] = infile.nextint();    count++; } 

Comments

Popular posts from this blog

user interface - How to replace the Python logo in a Tkinter-based Python GUI app? -

objective c - Greedy NSProgressIndicator Allocation -

how to set an OCR language in Google Drive -