我的源代码如下我正在尝试创建一个程序,当我的用户输入A,C或D时,它将计算圆的面积直径和圆周。我只想根据用户输入返回正确的响应。我设法让所有三个人在我的第一个案例中早些时候回归,但是将它们分开却难以理解?
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 :(得分: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;
}
...