I am trying to run the following program and am getting this error:

java.util.InputMismatchException

import java.io.*;

import java.util.*;

public class Pre2

{

static Scanner console = new Scanner(System.in);

public static void main(String[] args)throws IOException
{

Scanner inFile = new Scanner(new FileReader("Pre2Input.txt"));

PrintWriter outFile = new

PrintWriter(new FileWriter("Pre2Output.txt"));

int num1, num2;

num1 = inFile.nextInt();

num2 = inFile.nextInt();

outFile.println("Sum = " + (num1 + num2));

outFile.close();

}

}

What am I doing wrong? Pls help. Thanks in advanced :)

The error "java.util.InputMismatchException" occurs when the program is expecting a specific data type but receives a different type of data. In your case, it seems that the error is occurring while reading input from the file "Pre2Input.txt".

To troubleshoot this error, you can follow these steps:

1. Check the "Pre2Input.txt" file for any inconsistencies or formatting issues. Make sure that the file contains only integer numbers separated by spaces or newlines, as the program expects to read two integers.

2. Ensure that the file "Pre2Input.txt" exists in the correct location, i.e., in the same directory as your Java program.

3. Make sure there are no additional characters or unwanted spaces in the file. These can cause the program to read incorrect values or throw the InputMismatchException.

4. Double-check that the input values in the file are in a valid numerical format. For example, if the file contains non-numeric characters or letters instead of numbers, the InputMismatchException will occur.

5. If the above steps do not resolve the error, you can add exception handling to your code. Surround the section of code that reads the integers from the file with a try-catch block. This will catch any InputMismatchException and allow you to handle it gracefully. For example, you can display an error message or terminate the program elegantly instead of crashing.

Here's an example of how you can modify your code to add exception handling:

```java
try {
Scanner inFile = new Scanner(new FileReader("Pre2Input.txt"));

int num1 = inFile.nextInt();
int num2 = inFile.nextInt();

System.out.println("Sum = " + (num1 + num2));

inFile.close(); // Close the input file

} catch (IOException e) {
System.out.println("Error reading input file: " + e.getMessage());
} catch (InputMismatchException e) {
System.out.println("Invalid input format in the input file: " + e.getMessage());
}
```

By adding exception handling, you can identify the exact cause of the error and handle it accordingly.