在第15行ch = s1.charAt(0);
,
为什么 ch 没有得到 s1 的第 0 个字,即运算符 。
我尝试过不使用 try-catch 方法,但错误与异常有关
现在没有例外,没有错误,但程序不要求操作员并在输入后直接
第一个和第二个值,它显示异常“不能这样做”
请发表您的友好回复,谢谢
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();
}
}
你应该更换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();
如下b = sc.nextInt()
,它返回一个空字符串,因为它返回包含该 int 的行的末尾。当您尝试获取空字符串的第一个字符时,您会收到 IndexOutOfBoundsException。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)