【问题标题】:Java Switch displaying same dataJava Switch 显示相同的数据
【发布时间】:2018-06-23 10:48:15
【问题描述】:

我正在尝试根据用户输入的 3 或 4 或 5 来显示形状以拉出正确的形状,但输出一直显示triangle。这是我的代码:

import java.util.Scanner;

public class CodingAssignment_Week2 {
    public static void main(String[] args) {

        String userInputStringOfAngles;  // Declare a variable of type String to capture user input
        int numberOfAngles; // Declare a variable of type int to hold the converted user input

        Scanner myInputScannerInstance = new Scanner(System.in); // Recognize the keyboard
        System.out.print("Please type the integer 3, 4, or 5 and then press Enter: "); // Prompt the user
        userInputStringOfAngles= myInputScannerInstance.next(); // Capture user input as string
        numberOfAngles = Integer.parseInt(userInputStringOfAngles); // Convert the string to a number


    int num = 3;          // The num variable is set to 120
     if( num < 5 ) {        // Since 120 is NOT less than 50
                     //  the compiler will skip the next line and go directly to "else"          
             System.out.println("" ); }
     else  {               // Since 120 is greater than 50, the next code line will print.
              System.out.println("" );
     }
      int Num = 3;      // Declare numDayOfWeek and assign it 3, meaning the third day of the week
     String NumberOfAngles;     // Declare a variable of type String to hold the name of the day
     switch (Num) {   // Examine the value of numDayOfWeek variable
         case 3: NumberOfAngles = "A triangle has 3 sides."; // If numDayOfWeek is 1, then it must be Monday
                 break;
         case 4: NumberOfAngles = "A rectangle has 4 sides."; // If numDayOfWeek is 2, then it must be Thursday
                 break;
         case 5: NumberOfAngles = "A pentagon has 5 sides."; // etc.
                 break;

         default: NumberOfAngles = "Error! Please select integer 3, 4, or 5.";
                 break;
     }
     System.out.println(NumberOfAngles + ".");  

    }  
}

【问题讨论】:

    标签: java switch-statement


    【解决方案1】:

    您明确地将值 3 分配给 Num 。我建议避免只是从其他教程中复制粘贴代码,并在将其应用于您自己的代码之前先尝试了解该教程的工作原理。

    在您的示例中,您使用 Num 变量作为 switch 语句的计算表达式,而忽略用户的输入。

    这可以通过将userInputStringOfAngles 指定为表达式来解决。

    switch (numberOfAngles) {
        case 3:
            NumberOfAngles = "A triangle has 3 sides.";
            break;
        case 4:
            NumberOfAngles = "A rectangle has 4 sides.";
            break;
        case 5:
            NumberOfAngles = "A pentagon has 5 sides.";
            break;
    
        default:
            NumberOfAngles = "Error! Please select integer 3, 4, or 5.";
            break;
        }
    

    【讨论】:

      猜你喜欢
      • 2015-12-28
      • 1970-01-01
      • 1970-01-01
      • 2019-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-17
      相关资源
      最近更新 更多