-2

I have got the following code:

import java.util.Scanner;
import java.io.Serializable;
import java.io.*;

public class Application implements Serializable{

    private static Scanner input;

    public static void openInput()
    {
        try
        {
            input = new Scanner(new File("postings.txt"));
            input.useDelimiter("[,\\n\\r]");
            System.out.println("File opened(message1)");
        }
        catch(IOException ioe)
        {
            System.out.println("File has not opened" + ioe);
            System.exit(1);
        }
        System.out.println("File opened (message 2)");
    }

    public static void closeInput()
    {
        input.close();
        System.out.println();
    }

    public static void application()
    {
        Media[] arr = new Media[25];
        char type;
        String id, author;
        int views, likes, rebeeps, duration, shares;
        int numObjects = 0; 
        while(input.hasNext())
        {
            id = input.next();
            type = id.charAt(1);
            author = input.next();
            views = input.nextInt();
            if (type == 'B')
            {
                rebeeps = input.nextInt();
                likes = input.nextInt();
                arr[numObjects++] = new Beeper(type+id,author,views,rebeeps,likes);
            }
            else if(type == 'D')
            {
                duration = input.nextInt();
                shares = input.nextInt();
                arr[numObjects++] = new DingDong(type+id,author,views,duration,shares);
            }
            else
            {
                System.out.println("Incorrect code: " + arr[numObjects]);
            }
        }

        System.out.println("List of postings");
        for(int i = 0; i <= numObjects; numObjects++)
        {
            System.out.println(arr[numObjects]);
        }

        System.out.println("Scores of postings");
        for(int i = 0; i<= numObjects; numObjects++)
        {
            System.out.printf("%-8%7.2f",arr[numObjects].getID() + arr[numObjects].getAuthor() + arr[numObjects].calculateScore());
        }

        System.out.printf("%-8%7.2f",arr[numObjects].getID() + arr[numObjects].author + arr[numObjects]);

    }

    public static void main(String[] args)
    {
        openInput();
        application();
        closeInput();
    }
}

I have Three classes One superclass and two subclasses Superclass: Media subclasses: DingDong, Beeper

I am trying to get information from inside a textfile such as this: D123456,JohnD,28123,154,8045

and save it to the array according to their specific classes, But I get the following exception when I run Application:

File opened(message1)
File opened (message 2)
Incorrect code: null
Exception in thread "main" java.util.InputMismatchException
        at java.base/java.util.Scanner.throwFor(Scanner.java:939)
        at java.base/java.util.Scanner.next(Scanner.java:1594)
        at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
        at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
        at Application.application(Application.java:44)
        at Application.main(Application.java:82)

The variables in the code for the class Application are the same, and right, types as it is in the super and subclasses. Please help!

1 Answers1

0

Change your input delimiter to

input.useDelimiter("[,\n\r]+");

Carriage return and newline can sometimes be used together to signal end-of-line so you need to use the plus sign to use as many of the character class as required.

And change type = id.charAt(1); to type = id.charAt(0); since the first character starts at 0

Updated

I believe the problem is that if you get an invalid code, you have not read in extra values so they are out of order. Doing the following may help but it depends on whether those extra values are there in the event the type is not found.

            if (type == 'B') {
                rebeeps = input.nextInt();
                likes = input.nextInt();
            } else if (type == 'D') {
                duration = input.nextInt();
                shares = input.nextInt();
            } else {
                input.next(); // remove the lasts two values from the line
                input.next();
                System.out.println("Incorrect code:");
            }

Another solution would be to read in a line and then split on that line using commas and/or spaces as delimiters. In this case, if there are any errors in input, the line is ignored.

while (input.hasNextLine()) {
   String line = input.nextLine();
   String[] tokens = line.split("[,\\s]+");
   if (tokens.length != 5) {
      // print error message and take action (continue loop)
      continue;  // continue loop
   }  else {
      id = tokens[0];
      type = id.charAt(0);
      author = tokens[1];
      views = Integer.parseInt(tokens[2]);
    
      if (type == 'B') {
          rebeeps = Integer.parseInt(tokens[3]);
          likes =   Integer.parseInt(tokens[4]);
      } else if (type == 'D') {
          duration = Integer.parseInt(tokens[3]);
          shares = Integer.parseInt(tokens[4]);
      } else {
        System.out.println("Incorrect code:");
      }
}
WJS
  • 36,363
  • 4
  • 24
  • 39
  • Thanks! I changed the things you said but it still gives me the same exception. – JoubasaurusREX Jul 03 '23 at 19:44
  • Can you please post just the parsing part with some data and not any of the object creation, etc. I.e. read it in, assign it to variables, and continue. And please include more than one line of your input. Note that if one bit of data is out of order (i.e. a string is swapped for an int, you will get this error). I did test that delimiter and it worked fine with repeated lines of your data example. I presume you have no spaces in your lines. If you use a period instead of a comma you will also get that error. – WJS Jul 03 '23 at 19:46
  • That worked thanks for the help! – JoubasaurusREX Jul 03 '23 at 20:41