Как я могу добавить метод, который возвращает результат?

#java #return

#java #Возврат

Вопрос:

Я работал над этими программами. У них нет никаких ошибок, но мне нужно заставить их возвращать результат, чтобы они работали правильно. Более конкретно, чтобы добавить метод, который возвращает результат.

Инструкции были следующими: напишите программу, которая разделена на методы, по крайней мере, один из которых возвращает результат

Это первая программа:

 import java.util.Scanner; // Needed to make Scanner available

public class onlineCalculator {
    
   
    public static void main(String[] args) {
        Calculator();
} //END of main method
    
    // Inserting your loan at the start of the year and the amount paid off
    // and calculates the amount yet to pay with interest
    //
    public static void Calculator(){
        int a;
        int b;
        Scanner scanner = new Scanner(System.in);
        
        System.out.print("Amount of loan at start of year? ");
        a = scanner.nextInt();

        System.out.print("Amount paid off this year? ");
        b = scanner.nextInt();

        int c;
        c= a - b;

        double d;
        final double e;
        d = c * 1.07 * 10.0; 
        e = (int)d / 10.0; 
        
        System.out.println("The new amount owed is (in pounds): "   e);
     
    } //END of Calculator
}
  

Это вторая программа:

 import java.util.Scanner; // Needed to make Scanner available

public class BodyAge {

    public static void main(String[] args) {

        CalculateAge();
 
    } // END of main method

    // Inserting age and heart rate and stretch distance 
    //and calculates the body age based on conditions

    public static void CalculateAge() {
 
        int age;
        int heartRate;
        int stretch;

        Scanner input = new Scanner(System.in);

        System.out.print("What is your age? "); 

        age = input.nextInt();
 
        System.out.print("What is your heart rate? "); 

        heartRate = input.nextInt();

        if (heartRate <= 62) {
            age -= 5;          // block of code to be executed if condition1 is true
        } else if (62 <= heartRate amp;amp; heartRate <= 64) {
            age--;            // block of code to be executed if the condition1 is false and condition2 is
                              // true
        } else if (65 <= heartRate amp;amp; heartRate <= 70) {
            age  ;           // block of code to be executed if the condition1 and condition2 are false and 
                             // condition3 is true
        } else {
            age  = 2;       // block of code to be executed if the condition1 and condition2 and condition3
                            // are false and condition4 is true
        }

        System.out.print("How far can you stretch? "); 

        stretch = input.nextInt();
 
        if (stretch <= 20) {
            age  = 4;      // block of code to be executed if condition1 is true
        } else if (20 <= stretch amp;amp; stretch <= 32) {
            age  ;         // block of code to be executed if the condition1 is false and condition2 is
                           // true
        } else if (33 <= stretch amp;amp; stretch <= 37) {
            age = age   0; // block of code to be executed if the condition1 and condition2 are false and
                           // condition3 is true
        } else {
            age = age   3; // block of code to be executed if the condition1 and condition2 and condition3
                           // are false and condition4 is true
        }

        System.out.println("Your body's age is "   age);

    }  //END of CalculateAge
}
  

Комментарии:

1. » Написать программу, которая разделена на методы, по крайней мере, один из которых возвращает результат «, вряд ли является инструкцией. Вы уверены?

2. Видите void ключевое слово в ваших методах? Здесь вы должны указать, что ваш метод возвращает результат. Вы бы заменили void на примитивный тип или тип объекта, который вы хотите вернуть. public static int CalculateAge() например. Оттуда вы должны добавить return оператор, в котором вы завершаете метод и возвращаете значение. return age; например. Наконец, вы должны использовать возвращаемое значение. int age = CalculateAge(); System.out.println("Your body's age is " age); например, в вашем основном методе.

3. Удаление двух частей кода сделало ваш вопрос непоследовательным, потому что он все еще ссылался на них. Я отменил это.

4. Привет, онлайнкамерунибро. Пожалуйста, объясните, почему вы снова удалили части кода, на которые ссылается ваш вопрос. Если вы хотите удалить их, пожалуйста, отредактируйте формулировку вашего вопроса соответствующим образом. Кроме того, пожалуйста, убедитесь, что ваше редактирование не делает недействительным существующий ответ или не делает их странными для ссылки на «изобретенный» материал. Я отменю удаление, чтобы защитить ответы и сохранить последовательность вашего вопроса. Пожалуйста, объясните, прежде чем снова добавлять то, что вы опубликовали. Кстати, удаление больших частей вашего сообщения также рассматривается в соответствии с условиями соглашения и лицензирования здесь.

Ответ №1:

Вот пример одного из возможных способов, который вы могли бы рассмотреть, разбив класс на использование некоторых методов с возвратами. Давайте возьмем ваш первый класс для этого примера. Вы часто принимаете входные данные от своего пользователя.

 Scanner scanner = new Scanner(System.in);

System.out.print("Amount of loan at start of year? ");
a = scanner.nextInt();

System.out.print("Amount paid off this year? ");
b = scanner.nextInt();
  

Потенциально это может быть преобразовано в другой метод для сжатого повторного использования.

 public static int askForInt(Scanner scanner, String message) {
  System.out.print(message);
  return scanner.nextInt();
}
  

Оттуда вы можете заменить свои вызовы для получения информации этим методом. Полный пример:

 import java.util.Scanner; // Needed to make Scanner available

public class OnlineCalculator {

  public static void main(String[] args) {
    calculator();
  } //END of main method

  // Inserting your loan at the start of the year and the amount paid off
  // and calculates the amount yet to pay with interest
  //
  public static void calculator(){
    int a;
    int b;
    Scanner scanner = new Scanner(System.in);
    
    a = askForInt(scanner, "Amount of loan at start of year? ");
    b = askForInt(scanner, "Amount paid off this year? ");

    scanner.close();

    int c;
    c= a - b;

    double d;
    final double e;
    d = c * 1.07 * 10.0; 
    e = (int)d / 10.0; 
    
    System.out.println("The new amount owed is (in pounds): "   e);
 
  } //END of Calculator

  public static int askForInt(Scanner scanner, String message) {
    System.out.print(message);
    return scanner.nextInt();
  }
}
  

Ответ №2:

В первой программе вы могли бы, например, разделить свой метод calculate() на 2 метода и переместить переменную int «a» и «b» в метод main()

1-й метод:

 void getInput(){
...
}
  

2-й метод:

 int calculateAndreturnResult(int a, int b) {
...
}
  

Наконец, используйте этот метод в main() и распечатайте результат :

 getInput();
int result = calculateAndreturnResult(){
}

system.out.println(result);
  

Ответ №3:

Итак, как будет работать Java, компилятор будет считывать только команды из метода «main». Итак, в случае с калькулятором Java увидит, что вы хотите запустить метод calculator, который имеет возвращаемый тип «void», он становится ОБЩЕДОСТУПНЫМ (что означает, что другие классы могут видеть и взаимодействовать с ним), СТАТИЧЕСКИМ (в основном это означает, что метод принадлежит самому классу, а не экземплярамкласс) VOID (это ваш возвращаемый тип, то есть после завершения метода то, что возвращается обратно в main) поэтому, если вы хотите, чтобы метод что-то возвращал, вам нужно изменить возвращаемый тип. В случае вашего проекта calculator что-то вроде этого разделило бы его на 2 метода, один из которых возвращает что-то:

открытый класс OnlineCalculator {

 public static void main(String[] args) {
    Calculator();
  

} //КОНЕЦ основного метода

 // Inserting your loan at the start of the year and the amount paid off
// and calculates the amount yet to pay with interest
//

//this will return an int type
public static int loanDifference(int amountOwed, int amountPaid) {
    int c = amountOwed - amountPaid;
    return c;
}
  

// это вернет
публичный статический двойной тип double newAmountOwed(double d) {

      double e = (int)d / 10.0; 
     return e;
}

public static void Calculator(){
    int a;
    int b;
    Scanner scanner = new Scanner(System.in);
    
    System.out.print("Amount of loan at start of year? ");
    a = scanner.nextInt();

    System.out.print("Amount paid off this year? ");
    b = scanner.nextInt();
    scanner.close();

    int c = loanDifference (a, b);


    double d;
    d = c * 1.07 * 10.0; 
    final double e = newAmountOwed(d);
   

    
    System.out.println("The new amount owed is (in pounds): "   e);
 
} //END of Calculator
  

}

похоже, они хотят, чтобы вы добавили больше кода, но идея в том, что они хотят, чтобы вы знали, как использовать методы, которые работают вместе, чтобы сделать что-то в конце!

используйте ту же идею с другим!

Комментарии:

1. Эта программа не работает и выдает ошибки. Как я могу изменить его, чтобы он работал?