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!