2016-02-07 94 views
-2

我的源代碼如下我試圖創建一個程序,當我的用戶輸入A,C或D時將計算圓的面積直徑和圓周。我只想返回正確的響應取決於用戶的輸入。我設法讓所有三個人在早些時候回到我的第一個案例中,但是將他們分開證明很困難?Java混淆初始化變量在不同情況下的變量

import java.util.Scanner; 

public class Test { 

    public static void main(String[] args) { 
     Scanner sc = new Scanner(System.in); 
     System.out.print("This program will determine the Area, Circumference or Diameter for a circle. Type A for area C for Circumference and D for Diameter"); // Prompt for user input of capitol character 

     while (!sc.hasNext("[A-Z]+")) { 
      System.out.println(sc.next().charAt(0) + " is not a capital letter! Non Alphanumeric values are not permitted."); // error response for any unnaceptable character A-Z is specified as the range of acceptable characters 
     } 

     char c = ' '; 
     c = sc.next().charAt(0); // looking through user input at character at position 0 

     switch (c) { 

     case 'A': 
      System.out.print("Enter the radius: "); //I am storing the entered radius in floating point 
      float radius = sc.nextFloat(); 
      float area = ((float) Math.PI) * ((float)(radius * radius)); 
      System.out.printf("The area of the circle is: %.2f \n", area); 
      break; 

     case 'C': 
      System.out.print("Enter the radius: "); //I am storing the entered radius in floating point 
      float circumference = ((float)(Math.PI * 2 * radius)); 
      System.out.printf("The circumference of the circle is: %.2f \n", circumference); 
      break; 

     case 'D': 
      System.out.print("Enter the radius: "); //I am storing the entered radius in floating point 
      float diameter = ((float)(radius * 2)); 
      System.out.printf("The diameter of the circle is: %.2f \n", diameter); 
      break; 
     } 
    } 
} 
+0

怎麼樣放置一個',而(真)'將包含'而(!sc.hasNext( 「[AZ] +」) )'和你的'switch'? – aribeiro

回答

1

您定義和計算float radius = sc.nextFloat();case 'A':radius兩個其他情況下被使用。在一個開關中,只有一種情況被執行(當沒有下降時),因此,當你選擇'C'或'D'情況時,半徑變量從不定義,你會得到一個錯誤。

爲了解決這個問題,定義和計算radius開關外

... 

float radius = sc.nextFloat(); 
switch (c) { 

case 'A': 
    System.out.print("Enter the radius: "); //I am storing the entered radius in floating point 
    float area = ((float) Math.PI) * ((float)(radius * radius)); 
    System.out.printf("The area of the circle is: %.2f \n", area); 
    break; 

case 'C': 
    System.out.print("Enter the radius: "); //I am storing the entered radius in floating point 
    float circumference = ((float)(Math.PI * 2 * radius)); 
    System.out.printf("The circumference of the circle is: %.2f \n", circumference); 
    break; 

case 'D': 
    System.out.print("Enter the radius: "); //I am storing the entered radius in floating point 
    float diameter = ((float)(radius * 2)); 
    System.out.printf("The diameter of the circle is: %.2f \n", diameter); 
    break; 
} 
...