package labsheet1;
import java.util.Scanner;
public class Ques5 {
public static void main(String[] args) {
Scanner input = new Scanner(System. in );
int num1;
int num2;
int add, sub, mul, div;
int onum;
System.out.print("Enter first number :");
num1 = input.nextInt();
System.out.print("Enter second number :");
num2 = input.nextInt();
System.out.print("Enter operation number :");
onum = input.nextInt();
add = num1 + num2;
sub = num1 - num2;
mul = num1 * num2;
div = num1 / num2;
switch (onum) {
case 1:
System.out.println("Addition(+)");
System.out.println("The result is " + add);
break;
case 2:
System.out.println("Subtraction(-)");
System.out.println("The result is " + sub);
break;
case 3:
System.out.println("Multiplication(*)");
System.out.println("The result is " + mul);
break;
case 4:
System.out.println("Division(/");
System.out.println("The result is " + div);
break;
default:
System.out.println("None of the operations");
}
}
}
这是我的计划。现在我必须通过在程序结束时添加以下问题来修改它: 你想再做一次计算吗?
输入您的选项:
如果用户选择是(通过输入1),程序将再次要求他输入两个数字。如果不是,程序将退出。
我需要为此使用合适的循环。请帮忙。
答案 0 :(得分:1)
你可以试试这个
package labsheet1;
import java.util.Scanner;
public class Ques5 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int num1;
int num2;
int add,sub,mul,div;
int onum;
String ans = "Yes";
do
{
System.out.print("Enter first number :");
num1=input.nextInt();
System.out.print("Enter second number :");
num2=input.nextInt();
System.out.print("Enter operation number :");
onum=input.nextInt();
add=num1+num2;
sub=num1-num2;
mul=num1*num2;
div=num1/num2;
switch(onum)
{
case 1:
System.out.println("Addition(+)");
System.out.println("The result is " +add);
break;
case 2:
System.out.println("Subtraction(-)");
System.out.println("The result is " +sub);
break;
case 3:
System.out.println("Multiplication(*)");
System.out.println("The result is " +mul);
break;
case 4:
System.out.println("Division(/");
System.out.println("The result is " +div);
break;
default:
System.out.println("None of the operations");
}
System.out.print("Do you want to make another calculation?");
ans=input.nextLine();
}while(ans.toLowerCase().equals("Yes"));
}
}
答案 1 :(得分:0)
你可以使用Do-while
循环这个概念很简单:例如
String s;
do{
InetAddress ip;
try {
System.out.println("Hello here");
} catch (Exception e){
e.printStackTrace();
}
Scanner scan = new Scanner(System.in);
s = scan.next();
}while(s.toUpperCase().equals("Y") ||
s.toUpperCase().equals("YES"));
}
答案 2 :(得分:0)
它提示如何根据用户输入应用while循环继续处理: -
static String userChoice;
public static void main(String[] args) {
while (true) {
System.out.print("Do you want to make another calculation (Y/N)\n");
Scanner input = new Scanner(System.in);
userChoice=input.nextLine();
if (userChoice.equalsIgnoreCase("Y")) {
//Do your calculations
}
} else if (userChoice.equalsIgnoreCase("N")) {
System.out.print("Program is exiting. No more calculations!!!");
break;
} else {
System.out.print("Enter a valid choice (Y/N) only !");
}