I’m new to Java. I want to be able to input operational characters in a Scanner.
My code should produce the following,
- Enter two numbers: 13 6
- What operation? *
- What is 13 * 6? 78
- Correct!
I’m using a Switch-statement to store the operations available for the user.
Those are: +, -, * and /.
I recieve a run time error everytime I write an operation after the output.
import java.util.Scanner;
public class Användardialog4 {
public static void main(String[]args){
Scanner sc = new Scanner(System.in);
int svar;
String op;
char operator;
System.out.println("Enter two numbers: ");
int tal = sc.nextInt();
int tal2 = sc.nextInt();
System.out.println("Operation?");
op = sc.nextLine();
operator = op.charAt(0);
switch(operator){
case '+':
System.out.println("What is "+tal+" + "+tal2);
svar = sc.nextInt();
if (svar == tal+tal2)
System.out.println("Correct!");
else
System.out.println("Wrong - The right answer is: "+tal+tal2);
break;
case '*':
System.out.println("What is "+tal+" * "+tal2);
svar = sc.nextInt();
if (svar ==tal*tal2)
System.out.println("Correct!");
else
System.out.println("Wrong - The right answer is: "+tal*tal2);
break;
case '-':
System.out.println("What is "+tal+" - "+tal2);
svar = sc.nextInt();
if (svar == tal-tal2)
System.out.println("Correct!");
else
System.out.println("Wrong - The right answer is: "+(tal-tal2));
break;
case '/':
System.out.println("What is "+tal+" / "+tal2);
svar = sc.nextInt();
if (svar == tal/tal2)
System.out.println("Correct!");
else
System.out.println("Wrong - The right answer is: "+tal/tal2);
break;
}
}
}
The run time error I get is:
Exception in thread "main" java.util.InputMismatchException at
java.util.Scanner.throwFor(Unknown Source) at
java.util.Scanner.next(Unknown Source) at
java.util.Scanner.nextInt(Unknown Source) at
java.util.Scanner.nextInt(Unknown Source) at
Användardialog4.main(Dialog4.java:16)
So my question is, how do I use characters in a Scanner class?
Isn’t there a nextChar(); or something alike in Java?
Change
op = sc.nextLine();toop = sc.next();public String next();finds and returns the next complete token from this scanner. Since your operation is only one token/character, this is the way to go.public String nextLine();advances this scanner past the current line and returns the input that was skipped. Since you don’t have endline-character in your stream, this fails.