My code runs well,but it fails 3 test cases out of 6.
please help me to resolve this problem?
Test Case Failed.(Basic Calculator)
Hi Ajith,
Save your code on coding blocks ide and share a link to it.
here ,this is my code
import java.util.Scanner;
public class Cal {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
char ch = s.next().charAt(0);
while (ch != '+' && ch != '-' && ch != '*' && ch != '%' && ch != '/' && ch != 'x' && ch != 'X') {
System.out.println("Invalid operation. Try again.");
ch = s.next().charAt(0);
}
int c, a, b;
switch (ch) {
case '+':
a = s.nextInt();
b = s.nextInt();
c = a + b;
System.out.println(c);
break;
case '-':
a = s.nextInt();
b = s.nextInt();
c = a - b;
System.out.println(c);
break;
case '*':
a = s.nextInt();
b = s.nextInt();
c = a * b;
System.out.println(c);
break;
case '/':
a = s.nextInt();
b = s.nextInt();
c = a / b;
System.out.println(c);
break;
case '%':
a = s.nextInt();
b = s.nextInt();
c = a % b;
System.out.println(c);
break;
case 'X':
break;
case 'x':
break;
}
}
}
Hi Ajith,
See in this question you have to put all the switch block in a loop while or do-while where test condition will be ch != βxβ && ch != βXβ and put a default case for the condition when the input operation is not +,-,%,/ and * and print Invalid operation.
my code is giving an error like:
Exception in thread βmainβ java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at Main.main(Main.java:29)