2017-03-13 159 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字符的工作。

另一個測試可能是在之前打印「公式」開關,並檢查其內容。

相關問題