gpt4 book ai didi

java - Dr. Java 中的多个类

转载 作者:行者123 更新时间:2023-11-30 10:08:24 24 4
gpt4 key购买 nike

JDK 编译器说它可以编译,但是当它运行时我得到这个错误:

Static Error: This class does not have a static void main method accepting String[].

我习惯于将我的方法类放在一个文件中,而将主类放在一个单独的文件中。

我该如何解决这个问题?

    import java.util.Scanner;

public class Test{
private final int classSize = 35;
private int numEnrolled, numNeeded;

public void Input(){
Scanner in = new Scanner(System.in);
System.out.println("Enter the amount enrolled in your class");
numEnrolled = in.nextInt();
System.out.println("Your input is " + numEnrolled);

// Other parts of code that needs to be coded
}
}

class testRunner{
static void main(String args[]){
Test newTest = new Test();
newTest.Input();

}}

最佳答案

  • 在一个文件中你只能有一个公共(public)类,而多个非公开课
  • 您的文件名必须与唯一公开的相匹配类
  • 要使您的类可运行,它应该包含一个public staticvoid main(String args[])方法,最好在public类中

你的 TestRunner.java 应该是这样的

class Test{
private final int classSize = 35;
private int numEnrolled, numNeeded;

public void Input(){
Scanner in = new Scanner(System.in);
System.out.println("Enter the amount enrolled in your class");
numEnrolled = in.nextInt();
System.out.println("Your input is " + numEnrolled);

// Other parts of code that needs to be coded
}
}

public class TestRunner{
public static void main(String args[]){
Test newTest = new Test();
newTest.Input();

}}

编辑:如果你想保留文件名 Test.java,这也有效:

public class Test {
private final int classSize = 35;
private int numEnrolled, numNeeded;

public void Input() {
Scanner in = new Scanner(System.in);
System.out.println("Enter the amount enrolled in your class");
numEnrolled = in.nextInt();
System.out.println("Your input is " + numEnrolled);

// Other parts of code that needs to be coded
}
}

class TestRunner {
public static void main(String args[]) {
Test newTest = new Test();
newTest.Input();

}
}

关于java - Dr. Java 中的多个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53752676/

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