import java.util.Scanner;
public class Formula {
public static void main(String[] args) {
Scanner numIn = new Scanner(System.in);
Scanner form = new Scanner(System.in);
double r, d, h, a;
String formula;
System.out.println("Please state which circle formula you want to use:");
System.out.println("Circumference");
System.out.println("Area");
System.out.println("Cylinder volume");
formula = form.next();
switch (formula) {
case "Circumference":
System.out.println("Please state the diameter: ");
d = numIn.nextDouble();
System.out.println("The circumference is:");
System.out.println(3.14 * d);
break;
case "Area":
System.out.println("Please state the radius: ");
r = numIn.nextDouble();
System.out.println("The area is:");
System.out.println(3.14 * (r * r));
break;
case "Cylinder volume":
System.out.println("State the area of the base: ");
a = numIn.nextDouble();
System.out.println("State the height of the cylinder: ");
h = numIn.nextDouble();
System.out.println("the volume is: ");
System.out.println(a * h);
break;
default:
System.out.println("Option not recognized");
break;
}
}
}
正如你所看到的我試圖創建一個公式計算器(注意:我只是一個begginer),並且它似乎一直工作到最後一個'case'。當我在控制檯中輸入時,最後一種情況「Cylinder音量」無法識別。所有其他情況下工作正常,我沒有看到「氣缸容積」和其他的區別。請幫忙!爲什麼代碼不起作用?
使用'form.nextLine()'而不是'form.next()',否則你只會得到第一個單詞(「Cylinder」)。 – Zircon
*「爲什麼代碼不起作用」*是一個錯誤的標題。它可能適用於SO的大概90%以上的問題。你可能想要更具體。 – domsson
我想你需要知道[next()和nextLine()之間的區別](http://stackoverflow.com/questions/22458575/whats-the-difference-between-next-and-nextline-methods-from-掃描儀級)。並且爲了將來的需要,請[閱讀文檔](https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html) –