Java Switch, отображающий те же данные - PullRequest
0 голосов
/ 23 июня 2018

Я пытаюсь отобразить форму, основанную на вводе пользователем 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 + ".");  

    }  
}

1 Ответ

0 голосов
/ 06 августа 2018

Вы явно присваиваете значение от 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;
    }
...