2
我在Java中改寫了我還挺」第一個節目,現在它看起來像這樣:與do..while另一個問題
import java.util.*;
import static java.lang.Math.*;
public class FirstApp {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double a = 0;
double b = 0;
double c = 0;
double delta;
double x1 = 0, x2 = 0;
boolean repeat = false;
boolean decision = false;
System.out.println("Calculator 2.0");
System.out.println("Bartosz Kubacki 6.10.2016");
System.out.println("-------------------------------");
System.out.println("Welcome in Calculator 2.0 which helps you solve Ax^2 + Bx + C = 0.");
do
{
do
{
System.out.println("Enter A param (different from 0: ");
if(input.hasNextDouble())
{
a = input.nextDouble();
if(a == 0)
{
System.out.println("Param A needs to be different from 0!");
}
} else
{
input.nextLine();
System.out.println("Param A must be a number!");
}
} while(a == 0);
do
{
System.out.println("Enter B param: ");
if(input.hasNextDouble())
{
b = input.nextDouble();
repeat = false;
} else
{
input.nextLine();
System.out.println("Param B must be a number!");
repeat = true;
}
} while(repeat);
do
{
System.out.println("Enter C param: ");
if(input.hasNextDouble())
{
c = input.nextDouble();
repeat = false;
} else
{
input.nextLine();
System.out.println("Param C must be a number!");
repeat = true;
}
} while(repeat);
// Counting.. and showing results
delta = pow(b, 2) - (4 * a * c);
if(delta == 0)
{
x1 = (0 - b)/2 * a;
System.out.printf("There is one solution: %.2f\n", x1);
} else if(delta > 0)
{
x1 = ((0 - b) - sqrt(delta))/2 * a;
x2 = (b + sqrt(delta))/2 * a;
System.out.printf("There are two solutions: %.2f and %.2f\n", x1, x2);
} else
{
System.out.println("There is no solution.");
}
// Decyzja o kolejnych działaniach
do
{
System.out.println("Want make another eqation? [Y/N] ");
String dec = null;
if(input.hasNext("Y") || input.hasNext("N") || input.hasNext("y") || input.hasNext("n"))
{
dec = input.nextLine();
if(dec.equalsIgnoreCase("Y"))
decision = true;
else
decision = false;
repeat = false;
} else
{
input.nextLine();
repeat = true;
}
} while(repeat);
} while(decision);
input.close();
}
}
一切順利的話實際上只是:
當我把一個輸入A,B和C的值時,會顯示一個雙重警告,然後正常工作(只有一個警告)
當我回答Y或N時,程序終止,但如果我將輸入任何物品其他的如「g」「2」「w」等,然後程序再次詢問我(第一次也是兩次),然後當我輸入Y或N時,它工作得很好。
我真的不知道那是什麼約becouse存在編譯過程中沒有警告或錯誤。
感謝您的所有答案。 :)
如果您創建了一個輔助方法,例如,您的代碼將大大受益* 'promptDouble()',因此可以消除前3個大部分相同的循環。 – Andreas
下面是一個方法的例子,它提示安德烈亞斯建議http://stackoverflow.com/questions/39882635/how-to-find-out-which-variable-is-throwing-an-exception/39882790#39882790 – weston