所以我试图在控制台上创建一个Java计算器,它的工作正常,但是当我得到结果时,我希望它像循环一样重启,但我无法弄明白。
import java.util.Scanner;
public class calculator {
public static void main(String[] args0) {
Scanner test = new Scanner(System.in);
int x;
int y;
String c;
try {
System.out.println("Insert a number ");
x = test.nextInt();
System.out.println("insert a value e.g * / + -");
c = test.next();
System.out.println("Insert another number");
y = test.nextInt();
if (c.equals("*")) {
System.out.println("the total is " + x * y);
} else if (c.equals("+")) {
System.out.println("the total is " + (x + y));
} else if (c.equals("-")) {
System.out.println("the total is " + (x - y));
} else if (c.equals("/")) {
System.out.println("the total is " + (x / y));
} else {
System.out.println("you are an idiot");
}
} catch (Exception e) {
System.out.println("Please enter correct value.");
}
}
}
答案 0 :(得分:2)
使用while
+ break
。以下是工作版本:
import java.util.Scanner;
public class Calculator {
public static void main(String[] args0) {
Scanner test = new Scanner(System.in);
int x;
int y;
String c;
while (true) {
try {
System.out.println("Insert a number ");
x = test.nextInt();
System.out.println("insert a value e.g * / + -");
c = test.next();
System.out.println("Insert another number");
y = test.nextInt();
if (c.equals("*")) {
System.out.println("the total is " + x * y);
} else if (c.equals("+")) {
System.out.println("the total is " + (x + y));
} else if (c.equals("-")) {
System.out.println("the total is " + (x - y));
} else if (c.equals("/")) {
System.out.println("the total is " + (x / y));
} else {
System.out.println("you are an idiot");
}
} catch (Exception e) {
System.err.println("Please enter correct value.");
}
System.out.println("Do you wish to continue(y/n)?");
if (test.next().equals("n")) {
break;
}
}
}
}
答案 1 :(得分:1)
您可以使用while
循环:
public static void main(String[] args0) {
Scanner test = new Scanner(System.in);
while(true) {
....
}
如果要停止计算器,则需要输入ctrl - c
。
另一种方法,使用布尔值flag
并让用户自杀是否继续:
public static void main(String[] args0) {
boolean flag = true;
Scanner test = new Scanner(System.in);
while(flag) {
....
System.out.println("enter y for continue, n for exit");
c = test.next();
if (c.equals("n")) {
flag = false;
}
}
}
答案 2 :(得分:1)
在尝试之前插入while循环并将所有内容放在it.put while(true)中,这将无限重复。如果你想按某个键来停止make if条件并将其中断。
DECLARE @str VARCHAR(MAX)=''
DECLARE @where VARCHAR(max)=''''
IF 1>2
BEGIN
SET @where= 'Test_Group_Id=1'
END
ELSE
BEGIN
SET @where='Party_Master_Id=1'
END
SET @str = 'SELECT * FROM dbo.Party_Details WHERE 1=1 and ' + @where
EXECUTE(@str)