2016-02-07 39 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; 
} 
...