gpt4 book ai didi

Java方法代码错误

转载 作者:行者123 更新时间:2023-12-01 20:53:03 25 4
gpt4 key购买 nike

我试图对第二个返回方法进行两次调用,该方法接受一个参数(我的值以英寸为单位)并打印以厘米为单位的值,但它不起作用!我做错了什么?`

public static void main(String[] args) {
Scanner in = new Scanner(System.in);

// prompt the user and get the value
System.out.print("Exactly how many inches are you? ");
int uHeight = in.nextInt();

// converting and outputing the result
System.out.print("How many inches is your mother? ");
int mHeight = in.nextInt();
InchesToCm(mHeight,uHeight);
}

public static double InchesToCm() {


Scanner in = new Scanner(System.in);
System.out.print("Exactly how many inches are you? ");
int inHeight = in.nextInt();
double cmHeight = inHeight * 2.54;
System.out.println("He's " + uHeight + " inches or " + mHeight + " cm.");
return

最佳答案

您应该在方法中传递 mHeight 和 uHeight,因为您在主方法中调用它,如下所示 InchesToCm(mHeight,uHeight); 所以您的方法应如下所示:

public static double InchesToCm(int mHeight, int uHeight) {//pass your values in method

其次你必须最后返回结果:

return cmHeight;//return the result
<小时/>

注意

为了良好的实践,你的方法应该以小写字母开头,就像 @Timothy Truckle 在评论中所说,你的类名应该以大写字母开头

<小时/>

编辑

为了获得良好的实践,您必须使用:

public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Exactly how many inches are you? ");
int uHeight = in.nextInt();

System.out.println("He's " + uHeight + " inches or " + inchesToCm(uHeight) + " cm.");
System.out.print("How many inches is your mother? ");

int mHeight = in.nextInt();
System.out.println("He's " + mHeight + " inches or " + inchesToCm(mHeight) + " cm.");
//------------------------------^^-------------------------------^^------------------
in.close();//close your Scanner
}

//Your function should take inches and return cm
public static double inchesToCm(int height) {
return height * 2.54;
}

关于Java方法代码错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42853932/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com