问题
In the 15th line ch = s1.charAt(0);
,
why ch is not getting the 0th word of s1, i.e., the operator .
I've tried without using the try-catch method but then the error was regarding the exception
and now no exception, no errors but the program don't ask for operator and directly after inputting the 1st and 2nd value , it shows the exception"can't do that"
please post your kind replies, thanks
import java.util.Scanner;
class apples {
public static void calcu() {
try{
int a, b;
String s1;
char ch;
Scanner sc = new Scanner(System.in);
System.out.print("Enter the 1st value : ");
a = sc.nextInt();
System.out.print("Enter the 2nd value : ");
b = sc.nextInt();
System.out.print("Enter the operator : ");
s1 = sc.nextLine();
ch = s1.charAt(0);
System.out.println("yo");
switch(ch){
case '+' : System.out.print("sum is " + (a+b));
case '-' : System.out.print("Substraction is : " +(a-b));
case '*' : System.out.print("Multiplication is : " + (a*b));
case '/' : System.out.print("Multiplication is : " + (a/b));
default : System.out.print("wtf yo");
}
}
catch(Exception e) {
System.out.println("cant do that ");
}
}
public static void main(String args[]) {
apples obj = new apples();
obj.calcu();
}
}
回答1:
You should replace nextInt
with nextLine
:
System.out.print("Enter the 1st value : ");
a = Integer.parseInt(sc.nextLine());
System.out.print("Enter the 2nd value : ");
b = Integer.parseInt(sc.nextLine());
System.out.print("Enter the operator : ");
s1 = sc.nextLine();
ch = s1.charAt(0);
When s1 = sc.nextLine();
follows b = sc.nextInt()
, it returns an empty String, since it returns the end of the line that contained that int. When you try to get the first character of an empty String, you get an IndexOutOfBoundsException.
来源:https://stackoverflow.com/questions/27619851/indexoutofboundsexception-when-taking-character-input-from-the-user