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();
}
添加回答
舉報