[英]Quadratic Formula With User Input (Java)
我是編碼方面的新手,我不太確定如何100%寫出這個問題。 我試圖弄清楚為什么我的程序只存儲值“ a”的第一個輸入,即使該數字為負數也是如此。
例如:a = -1(值必須大於0。再次輸入值'a':) a = 1 b = 3 c = -4
因此,在程序編譯時,僅存儲了“ a”(-1)的第一個值,而不存儲第二個值(1),並且在遇到第二個if代碼塊時終止了程序。 我完全不知道如何解決這個問題:/
這是我的代碼:
package quadratic;
import java.util.*;
//Program that does quadratic equations
public class Quadratic{
public static void main(String[] args){
boolean run = true;
while(run){ //if program completes true, will start program again
Scanner sc = new Scanner(System.in); // set scanner to allow user input
System.out.println("Please enter value for 'a':");
double a = (sc.nextDouble()); //looking for user input
if (a <= 0){
System.out.print("Value must be greater than 0. Enter value 'a' again:\n");
sc.nextDouble(); //prompt user again if value less than or equal to 0
}
System.out.println("Please enter value for 'b':");
double b = (sc.nextDouble());
System.out.println("Please enter value for 'c':");
double c = (sc.nextDouble());
System.out.printf("Values entered: a:%s b:%s c:%s \n",a,b,c);
if (Math.pow(b,2)- (4 * a * c) <= 0){
System.out.println("Impossible. Program Terminating");
System.exit(0); //Terminate program
}
double qf1 = (-b + Math.sqrt(Math.pow(b, 2) - (4 * a * c))) / (2 * a);
double qf2 = (-b - Math.sqrt(Math.pow(b, 2) -(4 * a * c)))/ (2 * a);
// qf stands for Quadratic Formula
System.out.printf("Anwser One: %s \n", qf1); //%s whatever qf1 returned
System.out.printf("Anwser Two: %s \n", qf2); //%s whatever qf2 returned
}
}
}
你只是打電話
sc.nextDouble(); //prompt user again if value less than or equal to 0
不
a = sc.nextDouble(); //prompt user again if value less than or equal to 0
所以,您只是丟掉第二個數字
此外,您可以第二次輸入負數,因為您無需檢查該數字是否小於零(提示:可能是循環,直到輸入了有效的a
值?)
if (a <= 0){
System.out.print("Value must be greater than 0. Enter value 'a' again:\n");
sc.nextDouble(); //prompt user again if value less than or equal to 0
}
將上面的代碼替換為:
if (a <= 0){
System.out.print("Value must be greater than 0. Enter value 'a' again:\n");
a = sc.nextDouble(); //prompt user again if value less than or equal to 0
}
另外 ,您應該使用循環而不是if
語句,例如:
while (a <= 0){
System.out.print("Value must be greater than 0. Enter value 'a' again:\n");
a = sc.nextDouble(); //prompt user again if value less than or equal to 0
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.