如何在不使用参数的情况下调用方法

时间:2014-10-14 15:51:35

标签: java methods parameters

我不确定如何调用没有参数的方法或者为什么要这样做。有些变量尚未宣布,但我会在之后进行。该程序应该让用户输入他们的狗的体重,如果他们在LB中输入它,则将其转换为KG,然后计算喂狗的食物量。

import javax.swing.JOptionPane;
import java.util.Scanner; 
public class hakesgraemeA2Q1{

    public static void main(String args[])
    {
        double weightConversion = convertLBtoKG()
        double weightInLB =   
    }

    public static double convertLBtoKG(double weightInLB)
    {
        return weightInLB * 0.454;
    }


    public static double readWeight()
    {
        Scanner keyboard = new Scanner(System.in);
        String userInput = keyboard.nextLine();
        System.out.println("do you want to enter weight in kg or lb?, enter k for kg or p for lb ");
        if (userInput == "p"){
            System.out.println("enter your dogs weight in lb's:");
            return Math.round(keyboard.nextDouble() * weightConversion)/ 4f;
        }else if (userInput == "k"){
            System.out.println("enter your dogs weight in kg's:");
            return Math.round(keyboard.nextDouble())/4f;
        }else{
            System.out.println("i can't understant your choice; assuming kg:");  
            return Math.round(keyboard.nextDouble())/4f;
        }
    }
    public static double computeFoodAmount(double weightInKG)
    {
        if (weightInKG < 9.0){
            return weightInKG * 0.22;
        }else if (9.0 <= weightInKG && weightInKG < 32.0){
            return weightInKG * 0.18;
        }else if (32.0 <= weightInKG && weightInKG < 45.0){
            return weightInKG * 0.13;
        }else{
            return weightInKG * 0.09;
        }
    }
}

2 个答案:

答案 0 :(得分:0)

您无法使用String测试==平等,您可以使用String#equalsIgnoreCase(String)

if (userInput.equalsIgnoreCase("p")) {
  System.out.println("enter your dogs weight in lb's:");
  return Math.round(keyboard.nextDouble() * weightConversion)/ 4f;
} else if (userInput.equalsIgnoreCase("k")) {
  System.out.println("enter your dogs weight in kg's:");
  return Math.round(keyboard.nextDouble())/4f;
} else {
  System.out.println("i can't understant your choice; assuming kg:");  
  return Math.round(keyboard.nextDouble())/4f;
}

并将readWeight()的结果分配给weightInLB,您可以

double weightInLB = readWeight();

另外,这个

double weightConversion = convertLBtoKG()

要求将double传递给convertLBtoKG(),因为它需要double

答案 1 :(得分:0)

如果方法没有参数,则只有一组空括号,例如

double weight = readWeight();

如果您没有预见到所述方法具有不同的输入,则通常会使用不带参数的方法。参数通常是函数的输入,其中发生一堆东西,然后返回一个值。如果输入将是相同的,无论如何,那么可能没有用于参数。例如,在readWeight方法中,没有外部输入进入函数,因此没有参数是有意义的。但是,当调用方法时,您的convertLBtoKG方法需要外部输入,因为您必须将权重转换为正确的度量单位,然后将其返回。