请检查为什么我的代码给出了“错误的输入”语句以及正确的答案。虽然我在else块中使用过它...
import java.util.*;
public class Encapsulation {
public static void main(String args[]) throws InterruptedException {
Scanner sc = new Scanner(System.in);
System.out.print("Select operation(1:add, 2: sub): ");
int choose = sc.nextInt();
int a, b;
System.out.println("Enter 1st number: ");
a = sc.nextInt();
System.out.println("Enter 2nd number: ");
b = sc.nextInt();
choice(choose, a, b);
System.out.println("Do you want to calculate again(y/n): ");
char select = sc.next().charAt(0);
if (select == 'y') {
main(args);
} else {
System.out.println("Closing the program.........");
Thread.sleep(1000);
System.out.println("Program closed succesfully");
}
sc.close();
}
public static int add(int a, int b) {
return a + b;
}
public static int diff(int a, int b) {
return a - b;
}
public static void choice(int choose, int a, int b) {
if (choose == 1) {
System.out.println("The sum = " + add(a, b));
}
if (choose == 2) {
System.out.println("The diff = " + diff(a, b));
} else {
System.out.println("Wrong input!");
}
}
}
这是终端窗口的消息。请删除此“错误输入”消息
Select operation(1:add, 2: sub): 1
Enter 1st number:
10
Enter 2nd number:
10
The sum = 20
Wrong input! //This is the problem i don't want this statement
Do you want to calculate again(y/n):
将您的choice
方法更改为此:
public static void choice(int choose, int a, int b) {
if (choose == 1) {
System.out.println("The sum = " + add(a, b));
} else if (choose == 2) { // <---- u shd use else-if here
System.out.println("The diff = " + diff(a, b));
} else {
System.out.println("Wrong input!");
}
}
样本输出:
Select operation(1:add, 2: sub): 1
Enter 1st number:
10
Enter 2nd number:
10
The sum = 20
Do you want to calculate again(y/n):
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句