2017-03-13 163 views
-2
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音量”无法识别。所有其他情况下工作正常,我没有看到“气缸容积”和其他的区别。请帮忙!为什么代码不起作用?

+10

使用'form.nextLine()'而不是'form.next()',否则你只会得到第一个单词(“Cylinder”)。 – Zircon

+0

*“为什么代码不起作用”*是一个错误的标题。它可能适用于SO的大概90%以上的问题。你可能想要更具体。 – domsson

+0

我想你需要知道[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) –

回答

2

也就是说你使用

formula = form.next(); 

这只能读取,直到字的结束,而是不占空间 所以,当你把“气缸容积”它只读取缸。

,如果你将其更改为

formula = form.nextLine(); 
0

锆它将工作有解决方案。然而,它也可能会有所帮助在什么formula被设置为默认的情况下进行打印:

default: 
     System.out.println("Option: " + formula + " not recognized"); 
     break; 

做这种东西会帮助你的理智的未来。

0

尝试

Scanner form = new Scanner(System.in, "UTF-8").useDelimiter("\n"); 

请记住,扫描仪不能使用非ASCII字符的工作。

另一个测试可能是在之前打印“公式”开关,并检查其内容。

相关问题