首页 > 解决方案 > Java 初学者 - 需要 Java 代码错误建议

问题描述

首先,我是 Java 初学者。我终于要上大学的核心课程了。我在计算机科学 1 专业,我正在纠正从书中得到的代码作为练习,以便更好地了解如何修复代码。这是一个简单的代码,但是,我每次都会遇到 3 个错误。我需要有关如何纠正它们的建议!我对这一切都很陌生,所以有时会令人沮丧。谢谢!

public class Mistakes
{
    public static void main(String[] args);
    {
    int y;
    int x = 12;
    y + x = y;
    System.out.println("This is what y + x equals: "+y);
    System.out.print("This is what t equals: "+t);
    }
}

我一直遇到3个错误:

java:3: error: missing method body, or declare abstract
public void main(String[] args);
            ^


java:7: error: unexpected type
y + x = y;                     
  ^
required: variable
found:    value

java:9: error: cannot find symbol
System.out.print("This is what t equals: "+t);
                                           ^ 
symbol:   variable t
location: class Mistakes

t变成x? 我public class改成public abstract? 任何建议将不胜感激!

标签: java

解决方案


首先,您的main()方法;在声明之后有一个。仅当您声明的方法是抽象的并且因此没有“主体”时才允许这样做。在这种情况下,您应该删除分号。往下看:

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

其次,你的赋值操作是错误的。在 Java 中(以及一般的编程中),您必须首先指定一个变量,然后指定它将接收的值(字面意思,或者在您的情况下,通过表达式)。您应该如下所示执行此操作:

y = x + y; //the value of y will be equal to x+y

在这种情况下,您甚至可以使用快捷方式,如果您想:

y += x; //this expression will have the same effect as the shown above

最后,你得到了最后一个错误,因为变量t没有被声明,所以该方法System.out.print()试图打印一个不存在的变量。在这种情况下,您应该删除该符号t或使用此名称声明一个变量,如下所示:

int t = 3;
System.out.print("This is what t is equals to " + t); //t will be 3

推荐阅读