【问题标题】:Can anyone help me understand what is wrong with this code from my Java class [duplicate]谁能帮我理解我的Java类中的这段代码有什么问题[重复]
【发布时间】:2021-01-07 20:15:36
【问题描述】:

我不断收到同样的错误,这对我来说毫无意义。

Exercise03_01.java:5: error: class Exercise_03_01 is public, should be declared in a file named Exercise_03_01.java
public class Exercise_03_01 {

这是我的代码:

import java.util.Scanner;

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

    
        System.out.print("Enter a, b and c: ");
        // Prompt for user to enter the inputs
        
        double a = input.nextDouble();
        double b = input.nextDouble();
        double c = input.nextDouble();

        // Compute the discriminant of the equation.
        
        double discriminant = Math.pow(b, 2) - 4 * a * c;

        System.out.print("The equation has ");
        if (discriminant > 0)
        {
            double root1 = (-b + Math.pow(discriminant, 2)) / (2 * a);  
            double root2 = (-b - Math.pow(discriminant, 2)) / (2 * a);  
            System.out.println("two roots " + root1 + " and " + root2);
        }
        else if (discriminant == 0)
        {
            double root1 = (-b + Math.pow(discriminant, 2)) / (2 * a);
            System.out.println("one root " + root1);
        }
        else
            System.out.println("no real roots");
        }
    }

【问题讨论】:

  • 那么,代码是在一个名为exercise_03_01.java 的文件中吗?
  • 错误信息告诉你问题到底出在哪里。您的文件名需要与公共类的名称匹配。 Exercise03_01 != Exercise_03_01
  • 他们所说的或者你执行的地方是错误的。转到命令提示符/终端中的文件位置,然后运行它(使用cd file_directory 去那里)
  • @TheLegend42 我认为错误消息表明了这种情况下的问题。

标签: java


【解决方案1】:

您的班级与文件名不同。 声明公共类时,文件和类名必须相同(不包括 .java)

【讨论】:

    【解决方案2】:

    错误给了你答案。因为你的文件名不同。

    Exercise_03_01 类是公共的,应该在名为 Exercise_03_01.java 的文件中声明

    Public 类的文件名和名称必须相同。

    请将文件名更改为Exercise_03_01.java,它应该可以修复此错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-13
      • 1970-01-01
      • 2011-08-15
      • 2020-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多