gpt4 book ai didi

java - java中没有主要类型错误

转载 作者:行者123 更新时间:2023-12-01 12:27:13 24 4
gpt4 key购买 nike

这是源代码:

package feetToInches2;

public class Feet2Inches {
private double feetToInches_(double feet) {
return 12* feet;
}

private int max(int val1 int val2) {
if (val1 > val2) {
} else {
return (val2);
}
return 0;
}
}

当我尝试运行它时,它显示“选择不包含主类型”。我问过我的教授,他说有时 eclipse 会这样做,我需要做的就是重新启动我的计算机。这是真的吗?

最佳答案

你需要的是一个 main 方法。这是一个入口点

public static void main(String[] args) {
//Your code here
}

在您的情况下,它可能看起来像:

package feetToInches2;


public class Feet2Inches {
public double feetToInches_ (double feet) {
return 12* feet;
}

public int max(int val1, int val2) {
if (val1 > val2) {
return (val1);
}
else {
return (val2);
}
}
public static void main(String[] args) {
Feet2Inches converter=new Feet2Inches();
int max = converter.max(100,50);
double inches = converter.feetToInches_(10.5);
System.out.println("Max value = " + max);
System.out.println("Inches = " + inches);
}

}

我已经更改了您的方法修饰符,因此它会更有用。没有公共(public)方法的类是不需要的类;)我还修复了代码中的一些错误。

编辑:

如果您想让人们使用您的代码进行自己的计算,您有两种选择。您可以从 args 数组中获取参数,该数组保存程序运行时使用的参数。或者您可以在运行时提示输入数据。

1 使用参数

public static void main(String[] args) {
Feet2Inches converter = new Feet2Inches();
if (args.length != 3) {
System.err.println("Missing arguments! give me three numbers");
System.exit(1);//error exit
}
int val1 = Integer.valueOf(args[0]);
int val2 = Integer.valueOf(args[1]);
double val3 = Double.valueOf(args[1]);
int max = converter.max(val1, val2);
double inches = converter.feetToInches_(val3);
System.out.println("Max value from (" + val1 + "," + val2 + ")= " + max);
System.out.println(val3 + "Feet = " + inches + " inches");
}

现在你必须用参数 Here 调用你的程序你可以从 cmd 和 Here 看到如何做到这一点是如何在 Eclipse 中做到这一点

2 在运行时询问用户参数

public static void main(String[] args) {
Feet2Inches converter = new Feet2Inches();
Scanner input = new Scanner(System.in);
System.out.print("Argument 1:");
int val1 = input.nextInt();
System.out.print("Argument 2:");
int val2 = input.nextInt();
System.out.print("Argument 3:");
double val3 = input.nextDouble();
int max = converter.max(val1, val2);
double inches = converter.feetToInches_(val3);
System.out.println("Max value from (" + val1 + "," + val2 + ")= " + max);
System.out.println(val3 + "Feet = " + inches + " inches");
}

关于java - java中没有主要类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26231781/

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