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) –