3 回答

TA贡献2019条经验 获得超9个赞
所以你正在寻找的是循环的想法。存在三种基本类型的循环。
一个for循环。常用于loopa 之上Collection,例如 an ArrayList, Map, or Array。其语法通常如下所示:
for (int i = 0; i < someSize; i++){ }
一个while循环。当您不知道循环何时退出时,通常用于循环。简单循环的语法如下所示:
boolean condition = true;
while(condition) {
//Code that will make condition false in a certain scenario
}
一个do while循环。while当您确定希望代码块至少运行一次时,这是循环的一种变体。示例如下:
boolean condition = //can be set default to true or false, whichever fits better
do{
//Any code you want to execute
//Your code that will determine if the condition is true or false
} while (condition);
循环do while最适合您的程序,因为您希望每次运行程序时至少运行一次。所以你需要做的就是将它放在一个循环中并创建你的条件。
我让你从下面的骨架开始:
Scanner sc = new Scanner(System.in);
int choice = 0;
do{
System.out.println("Hi, I am being repeated until you tell me stop!"); //Replace this with your code
System.out.println("Enter 1 to run the program again, 0 to exit.");
choice = sc.nextInt();
}while (choice == 1);
sc.close();

TA贡献1776条经验 获得超12个赞
您可以在 main 方法中添加类似的内容,但将所有内容复制到此 while 中,现在您的代码将一直运行,直到您终止该进程。
while(true){
System.out.println("My project");
System.out.println("Project_2 Problem_1\n");
System.out.println("This program computes both roots of a quadratic equation,\n");
System.out.println("Given the coefficients A,B, and C.\n");
double secondRoot = 0, firstRoot = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the value of a ::");
double a = sc.nextDouble();
System.out.println("Enter the value of b ::");
double b = sc.nextDouble();
System.out.println("Enter the value of c ::");
double c = sc.nextDouble();
double determinant = (b*b)-(4*a*c);
double sqrt = Math.sqrt(determinant);
if(determinant>0)
{
firstRoot = (-b + sqrt)/(2*a);
secondRoot = (-b - sqrt)/(2*a);
System.out.println("Roots are :: "+ firstRoot +" and "+secondRoot);
}else if(determinant == 0){
System.out.println("Root is :: "+(-b + sqrt)/(2*a));
}
}
我没有给你完整的答案,但请注意,如果你修改此代码以询问你的用户的一些输入,你可以为 while 循环设置不同的条件并根据用户输入启动和停止你的程序。

TA贡献1804条经验 获得超7个赞
将所有代码放入一个单独的方法中,然后提示用户并询问用户是否要再次运行该程序。这种对同一个方法的重复调用称为递归。
让我们调用方法运行。
public static void run() {
** put all the code from your main method here **
Scanner s = new Scanner(System.in);
System.out.println("Would you like to run program again? (Y for yes, N for no)");
String decision = s.next();
if(decision.equals("Y")) {
run();
} else {
System.out.println("Finished");
}
}
public static void main(String args[]) {
run();
}
添加回答
举报