Java - проблема с циклом преобразования температуры - PullRequest
0 голосов
/ 21 октября 2018

Я делаю небольшое упражнение по программированию на Java.

По сути, приложение позволяет пользователю вводить температуру по Фаренгейту и отображает значение в градусах Цельсия или вводить температуру в градусах Цельсия и отображает эквивалент в градусах Фаренгейта.Приложение включает в себя метод Цельсия, который возвращает Цельсий эквивалент температуры по Фаренгейту.Приложение также включает метод Фаренгейта, который возвращает градус Фаренгейта, эквивалентный температуре Цельсия.

Вот мой полный код:

import java.util.Scanner;

public class Temperature{

    public static void main(String[] args) {  // Main Method//

        Scanner input = new Scanner(System.in);

        //Declare variables
        int choice; // the user's choice in the menu //
        int temp;   

        do   {

             // print the menu

                System.out.println("1.fahrenheit to Celsius"); 
                System.out.println("2.Celsius to Fahrenheit"); 
                System.out.println("3.Exit"); 
                System.out.println(""); 
                System.out.println("Choice:");

             choice = input.nextInt();


             if  ( choice != 3 ) {

         System.out.print( "Enter temperature: " ); // Display Enter Temperature
         temp = input.nextInt();  // Read Temperature


         if (choice == 1) {

             System.out.println( temp +  " Fahrenheit is " + toCelsius( temp ) + " Celsius ");
             System.out.println("");
         }

         else if (choice == 2 ) {
             System.out.println(temp + " Celsius is " +  toFahrenheit( temp ) + " Fahrenheit ");
             System.out.println("");

          } 

         else {
             System.out.println("Program terminated ");   //  Display "Program terminated" if user entered 3
             }

        }  //end if loop

        } // end do loop
        while (choice !=3);

    }  // end main method



    // return Celsius equivalent of Fahrenheit temperature
         public static int    toCelsius(int  fahrenheit) {
             int   celsius;
             celsius = (int) (5.0/9.0 * (fahrenheit - 32));
             return celsius;
           }  // end method celsius


         // return Fahrenheit equivalent of Celsius temperature
         public static int    toFahrenheit(int  celsius) {
             int   fahrenheit;
              fahrenheit = (int) (9.0/5.0 * celsius + 32);
             return fahrenheit;
           } // end method fahrenheit



    } 

Хорошо, что код, включающий методы, работает.Пользователь может ввести вариант 1 или 2, а затем ввести номер температуры и отобразить его в градусах Цельсия или Фаренгейта.Но если пользователь введет вариант 3, программа отобразит «Программа остановлена».Для меня, когда я ввел вариант 3, программа перестала работать (не отображалось «Программа остановлена»).Я думаю, что есть проблема в части 'loop' или 'IF'.

Может кто-нибудь помочь мне с этим?

Ответы [ 2 ]

0 голосов
/ 21 октября 2018

Вы включили все в if (choice! = 3), поэтому, даже если вы ввели в качестве выбора значение 3, остальное, включая Программу, будет прекращено.Так что просто реорганизуйте скобки, и все будет работать нормально.

import java.util.Scanner;

public class Temperature{

   public static void main(String[] args) {  // Main Method//

       Scanner input = new Scanner(System.in);

    //Declare variables
       int choice; // the user's choice in the menu //
       int temp;   

       do   {

            // print the menu

               System.out.println("1.fahrenheit to Celsius"); 
               System.out.println("2.Celsius to Fahrenheit"); 
               System.out.println("3.Exit"); 
               System.out.println(""); 
               System.out.println("Choice:");

            choice = input.nextInt();


            if  ( choice != 3 ) {

              System.out.print( "Enter temperature: " ); // Display Enter Temperature
              temp = input.nextInt();  // Read Temperature


              if (choice == 1) {

                  System.out.println( temp +  " Fahrenheit is " + toCelsius( temp ) +" Celsius ");
                  System.out.println("");
              }

              else if (choice == 2 ) {
                  System.out.println(temp + " Celsius is " +  toFahrenheit( temp ) + " Fahrenheit ");
                  System.out.println("");

              } 

            }
            else {
             System.out.println("Program terminated ");   //  Display "Program terminated" if user entered 3
           }//end else loop

       } // end do loop
       while (choice !=3);

   }  // end main method



// return Celsius equivalent of Fahrenheit temperature
   public static int    toCelsius(int  fahrenheit) {
       int   celsius;
       celsius = (int) (5.0/9.0 * (fahrenheit - 32));
        return celsius;
   }  // end method celsius


     // return Fahrenheit equivalent of Celsius temperature
     public static int    toFahrenheit(int  celsius) {
         int   fahrenheit;
          fahrenheit = (int) (9.0/5.0 * celsius + 32);
         return fahrenheit;
       } // end method fahrenheit

  }
0 голосов
/ 21 октября 2018

Ваша логика неверна.У вас есть внешний оператор if, который вводится только в том случае, если пользователь не вводит три.Поэтому, если вы это сделаете, else во внутреннем if не будет выполнен, и, таким образом, ваше сообщение никогда не будет напечатано:

//If you do enter three, it will skip over all of this:
if  ( choice != 3 ) {

     System.out.print( "Enter temperature: " ); // Display Enter Temperature
     temp = input.nextInt();  // Read Temperature


     if (choice == 1) {

         System.out.println( temp +  " Fahrenheit is " + toCelsius( temp ) + " Celsius ");
         System.out.println("");
     }

     else if (choice == 2 ) {
         System.out.println(temp + " Celsius is " +  toFahrenheit( temp ) + " Fahrenheit ");
         System.out.println("");

      } 
     else {   
         System.out.println("Program terminated ");   //  Display "Program terminated" if user entered 3
     }

}

Вам необходимо удалить внешнее if или, в качестве альтернативы, переместитьблок else после внешнего if.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...