-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;
}
}
}
怎麼樣放置一個',而(真)'將包含'而(!sc.hasNext( 「[AZ] +」) )'和你的'switch'? – aribeiro