1

I have a file with multiple fields that i need to store individually into an array.

Steve;stiffy;123;88
Sam;sammy;456;55

But when i try storing them i keep getting error saying java.util.NoSuchElementException

Here is my code for storing the data

void loadCustomer(){

    try {
        Scanner sc = new Scanner(new File("CustomerInfo.txt"));
        sc.useDelimiter(";");
        while (sc.hasNext())
        {
            cusName.add(sc.next());
            cusUser.add(sc.next());
            cusPass.add(sc.next());
            cusCCNum.add(sc.next());
        }
}

I could get it to work by changing

cusCCNum.add(sc.next());

to

cusCCNum.add(sc.nextLine());

but it will ignore the delimiter and when i print out cusCCNum.get(1), it will display

;88

instead of

88

Where did i go wrong?

user1958567
  • 67
  • 1
  • 6

4 Answers4

4

There is no delimiter between 88 and Sam..

  scanner.useDelimiter(";|\n");
Eugene
  • 117,005
  • 15
  • 201
  • 306
2

Use String tokenizer instead of delimiter. Get input as a string and parse it by ; character as token.

Learn, how to use stringtokenizer here

Tugrul
  • 1,760
  • 4
  • 24
  • 39
0

You are causing the exception while you are calling the 4 next elements for each one check if there is 1 next element, this would do the following:

while (RecentElement is not the last one)
{
    Read (RecentElement + 1)
    Read (RecentElement + 2)
    Read (RecentElement + 3)
    Read (RecentElement + 4)
}

And somewhen you get the exception of the next() method because you access an element that is just not there:

Throws: NoSuchElementException - if no more tokens are available

You should use the new line as a delimiter and for each new line parse the data from the record, for example using the split function:

   sc.useDelimiter("\n");      
   while (sc.hasNext())
   {
       for(String g: sc.next().split(";"))
         System.out.println(g);          
   }
CloudyMarble
  • 36,908
  • 70
  • 97
  • 130
0

Looks like you need to read each line, token it using delimeter and set values to array.

I could do it via StringTokenizer.

while (sc.hasNextLine())            {               
                StringTokenizer st =  new StringTokenizer(sc.nextLine(),";");               
                while (st.hasMoreElements()) {
                    System.out.println(st.nextElement());
                }
            }

I am surprised and need to read more on Scanner api to see why its not working with scanner.

sudmong
  • 2,036
  • 13
  • 12