jeudi 12 mars 2015

java.util.InputMismatchException while using java.util.Scanner



I'm stuck on an assignment:



Using Netbeans, write a class called IO, in a package called util, containing the methods: getInput(String), getConsoleInput(String), showMessage(String), and showMessage(String, String).

The method getInput(String) will be through GUI, the method getConsoleInput(String) will input/output through the console and return a Scanner object.

The showMessage(String, String) will accept a title for the output dialog.


Then write a program using the IO class, but in a separate file and in the default package. Your program will first ask the user to enter 2 integers. If both are positive, print the sum. Then it will ask for 2 real numbers(float or double); if only one is negative, print the product of the 2 numbers. If both are negative, print the quotient. Use nested if's where possible.


Output must be formatted. And all input/outputs must be done through the methods you created. All output is to be done through console and dialog.



I believe that I've written my methods correctly, but when my program codes calls them, I get multiple exceptions AFTER I respond to the dialog box.


Exception:



Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at Assignment4.main(Assignment4.java:18)


Java-Code:



public class Assignment4 {
public static void main(String[] args) {
Scanner scan = IO.getInput("Enter 2 integers");
int x = scan.nextInt();
int y = scan.nextInt();

if (x > 0 && y > 0)
IO.showMessage(String.format("The sum is: %6.2d", (x + y)));
}
}



Aucun commentaire:

Enregistrer un commentaire