Java encountering runtime errors while trying to read text file

I'm currently trying to write a Java assignment that is supposed to, in order;

  • Read each line of a prewritten text file
  • Turn each line into a string
  • Turn each part of each line into its own individual string/int/double
  • Assign those variables in an object (Which is part of an array of objects) of a class which I have also created as part of this assignment
  • Print each variable of the object using one of the class' methods
  • However, I am repeatedly running into a runtime problem where I am getting this error message;

    Exception in thread "main" java.util.NoSuchElementException at java.util.Scanner.throwFor(Scanner.java:862) at java.util.Scanner.next(Scanner.java:1371) at Lab2.main(Lab2.java:27)

    This leads me to believe I am probably reading the text file wrong. However, no matter what I do I can't seem to get it to read correctly. It's supposed to read a first name, a last name, three separate components of an address (which it concatenates into one string), a city, a state, a zip code (as an integer), a phone number (as a string) and a dollar amount (as a double).

    I believe that the problem might arise from the city names, as some of them have a space between them. I thought I had solved this by setting the delimiter of the Scanner that reads each individual string to a tab (which is what every other element is separated by) but this has either not worked (And is thus trying to turn state names into an integer via the Integer.parseInt() static method) or is not the problem. As I said, I am out of ideas and would be greatly appreciative towards anyone who could help me out here!

    I will list the code below. First here is the main file;

    public class Lab2
    { 
        public static void main(String[] args) throws IOException
        { String FirstName, LastName, Address1, Address2, Address3, AddressFull, City, State, Phone, ZipString, DonString, line = "blank";
          int Zip;
          double Donation;
    
          Scanner fileScan = new Scanner(new File("Lab2.txt")), lineScan = new Scanner(line);
          lineScan.useDelimiter("t");
    
          PersonStats[] Donators = new PersonStats[25];
    
          for (int i = 0; i < Donators.length; i++)
          { line = fileScan.nextLine();
    
            FirstName = lineScan.next();
            LastName = lineScan.next();
    
            Address1 = lineScan.next();
            Address2 = lineScan.next();
            Address3 = lineScan.next();
            AddressFull = Address1 + " " + Address2 + " " + Address3;
    
            City = lineScan.next();
            State = lineScan.next();
    
            ZipString = lineScan.next();
            Zip = Integer.parseInt(ZipString);
    
            Phone = lineScan.next();
    
            DonString = lineScan.next();
            Donation = Double.parseDouble(DonString);
    
            Donators[i] = new PersonStats(FirstName, LastName, AddressFull, City, State, Zip, Phone, Donation);
            Donators[i].PrintOut();
          }
    
        }
    }
    

    Next, the class file I've written up for the assignment;

    public class PersonStats
    { private String FirstName, LastName, Address, City, State, Phone;
    private int Zip;
    private double Donation;
    
    public PersonStats(String first, String last, String area, String town, String feifdom, int postcode, String telegraph, double given)
    { FirstName = first;
      LastName = last;
      Address = area;
      City = town;
      State = feifdom;
      Zip = postcode;
      Phone = telegraph;
      Donation = given;
    }
    
    public void PrintOut()
    { System.out.println(FirstName + " " + LastName);
      System.out.println(Address);
      System.out.println(City + ", " + State + " " + Zip + "n");
      System.out.println(Phone + " " + Donation);
    }
    
    }
    

    And then finally the text file the program is supposed to be reading from (Might be a little bit difficult to read, just remember each space except for the ones in city names is actually a tab);

    Rick    James   8276    Carlos  Ave Las Vegas   NV  87126   5553451567  23.95
    John    Gibson  9127    Oak Dr  Corvallis   OR  97330   5552812313  156.78
    Ron Wills   1155    Ivy Pl  Atlantic    Ga  37339   5552123145  189.56
    Rita    Jones   1259    Chase   Ave Las Vegas   NV  87126   5554445671  2145.60
    Jason   Knight  7154    Pine    Dr  Gresjam     OR  97380   5558124545  3157.44
    Clara   Swanson 1944    Main    Pl  Springfield OR  97339   5552123144  212.99
    Robert  Peck    1866    First   Ave Las Vegas   NV  87126   5553455425  250.00
    Dora    Garcia  2179    Fir Dr  Corvallis   OR  97330   5552812919  350.00
    Peter   Keck    1465    Circle  Pl  Gold Beach  OR  97339   5552123256  2150.00
    Stuart  Smith   2387    Sweek   Ave Las Vegas   NV  87126   5553455489  650.99
    Tyler   Wild    1313    Spooky  Ln  Corvallis   OR  97330   5552813213  587.45
    Laretta Peters  2224    Chase   Pl  Monmouth    OR  97361   5552124465  123.45
    Kristi  Emry    3465    Cerrito Ave Las Vegas   NV  87126   5553455567  3212.65
    Kelli   Gard    1894    Elm Dr  Corvallis   OR  97330   5552816678  51.00
    Jacob   Andrews 8159    Rose    Ct  Mill City   OR  97322   5552127879  64.00
    Ryan    Perkins 7546    Prince  Ave Las Vegas   NV  87126   5553451989  13.00
    Joshua  Gilbert 9278    Monroe  Dr  Corvallis   OR  97330   5552832656  95.00
    Miles   Crain   4578    Chester Dr  Corvallis   OR  97331   5552345678  1544.00
    Butch   Cassidy 5498    Sutton  Pl  Gresham     OR  97380   5416565797  1798.56
    Perry   Winkle  8185    Shaver  Ave Las Vegas   NV  87126   5553812346  195.66
    Loni    Day 4598    Holmen  Dr  Corvallis   OR  97330   5555289741  1878.50
    Nikita  Benson  1787    Grant   Pl  Portland    OR  97321   5553569898  1500.00
    Rusty   Krouger 8829    Simeon  Ave Las Vegas   NV  87126   5555677847  2100.00
    Wally   Wallace 2898    Wilson  Blvd    Jackson Center  OH  23466   5552222222  2222.22
    Joe     Jones   1212    Water   St  Millersburg OR  97366   5555555555  55.55
    

    Again, thanks in advance if there's anyone out there who can help me with this, your advice might save a life!... or at least the score of this lab :S


    Okay, here it is

    import java.io.IOException; 
    import java.io.*;
    import java.util.Scanner;
    public class Lab2
    { 
        public static void main(String[] args) throws IOException
        { String FirstName, LastName, Address1, Address2, Address3, AddressFull, City, State, Phone, ZipString, DonString, line = "blank";
          int Zip;
          double Donation;
    
          Scanner fileScan = new Scanner(new File("F:/test.txt")).useDelimiter("n");
    
          PersonStats[] Donators = new PersonStats[5];
          String tempVal="";
          int i = 0;
          while(fileScan.hasNext())
          {
            tempVal = fileScan.next();  //Storing person records one at a time in the string line by line
            String tempArr[] = tempVal.split("t"); //Splitting each person record string by tab and storing it in a String array
    
                FirstName = tempArr[0];
                LastName = tempArr[1];
    
                Address1 = tempArr[2];
                Address2 = tempArr[3];
                Address3 = tempArr[4];
                AddressFull = Address1 + " " + Address2 + " " + Address3;
    
                City = tempArr[5];
                State = tempArr[6];
    
                ZipString = tempArr[7];
                Zip = Integer.parseInt(ZipString);
    
                Phone = tempArr[8];
    
                DonString = tempArr[9];
                Donation = Double.parseDouble(DonString);
                Donators[i] = new PersonStats(FirstName, LastName, AddressFull, City, State, Zip, Phone, Donation);
                Donators[i].PrintOut();
                i++;
          }  
        }
    }
    

    First of all, I would like to point out that your variable names should start with lower case. I did not edit them in the code since they were used in many places. Make an habit to declare String firstName instead of String FirstName

    To the code, in your code you had used a "t" delimter which I replaced with "n" since in the text file each line holds entire Person details. You could have used "t" if the donation of the first person and first name of the second person were separated by the same, but they are separated by "n"

    So now Scanner fileScan will read the file line by line which I will store in String tempVal and while(fileScan.hasNext()) assures that the Scanner will keep reading only as long as there are lines to be read.

    Now, every line has different information separated by "t" . So I used tempVal.split("t") to separate them. Also, used a counter int i and removed the for loop. I guess rest of the code is pretty basic and not much different from yours.

    **EDIT****

    Here is the output

    Rick James
    8276 Carlos Ave
    Las Vegas, NV 87126
    
    5553451567 23.95
    John Gibson
    9127 Oak Dr
    Corvallis, OR 97330
    
    5552812313 156.78
    Ron Wills
    1155 Ivy Pl
    Atlantic, Ga 37339
    
    5552123145 189.56
    Rita Jones
    1259 Chase Ave
    Las Vegas, NV 87126
    
    5554445671 2145.6
    Jason Knight
    7154 Pine Dr
    Gresjam, OR 97380
    
    5558124545 3157.44
    

    And here is the sample text.file that I used.

    Rick    James   8276    Carlos  Ave Las Vegas   NV  87126   5553451567  23.95
    John    Gibson  9127    Oak Dr  Corvallis   OR  97330   5552812313  156.78
    Ron Wills   1155    Ivy Pl  Atlantic    Ga  37339   5552123145  189.56
    Rita    Jones   1259    Chase   Ave Las Vegas   NV  87126   5554445671  2145.60
    Jason   Knight  7154    Pine    Dr  Gresjam OR  97380   5558124545  3157.44
    

    here is a tip: When using Scanner use the hasNextXXX method before invoking next methods to check if elements exists

    https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

    No Such Element Exception?


     Scanner fileScan = new Scanner(new File("Lab2.txt"));
    
    
          //PersonStats[] Donators = new PersonStats[25];
    
          while(fileScan.hasNext()) {
    
    
             line = fileScan.nextLine();
    
            String parts[] = line.split("t");        
    
            if(parts.length == 10) {
    
                FirstName = parts[0];
    
    
                ...
            }
    

    There are some problems in addion. First: String ist immutable. So your lineScanner will created with an empty String. If you later change this string, nothing appens for this scanner, because you create a new string with this step.

    Second you have to check for an next element. (see my while loop)

    To parse your data it is easyer to split the string in parts and use this to fill your Class. But if you want to use the Scanner class, you have to create on instance per line in your file.(in the while loop)

    链接地址: http://www.djcxy.com/p/96094.html

    上一篇: 我的扫描仪代码有什么问题?

    下一篇: Java尝试读取文本文件时遇到运行时错误