java - 如何消除错误 : illegal start of type in java?

标签 java arrays

我是编码新手,所以请耐心等待。在我的代码中,我在 for 循环(位于学生类(class)中)中遇到非法开始类型错误。我该如何修复这个错误?

在我的 for 循环中,我想让我的数组 Grades 有 10 个值(已经定义),这些值将从 60 到 99 随机。在我看来,我认为这部分是正确的,并且自始至终我都使用了正确的方法。因此,如果有人能看到我哪里出了问题,我将非常感激:)

import javax.swing.*;

public class StudentBase
{
  public static void main(String[] args){
      StudentBase app = new StudentBase();
      app.go();
    }

    void go(){
        //this is the main routine
         JOptionPane.showMessageDialog(null, "Welcome!" + '\n');

         String n = JOptionPane.showInputDialog("Type in your name");
         JOptionPane.showMessageDialog(null, "Press ok if your name is" + " " +  n);

         String h = JOptionPane.showInputDialog("What is your height? (in meters: eg - 1.80)");
         JOptionPane.showMessageDialog(null, "Press ok if your height is" + " " + h + " " + "meters");

         JOptionPane.showMessageDialog(null, "Introduction to student class:" + " " + "Hello! My name is" + " " + n + " " + "and I am" + " " + h + " " + "meters tall.");

         String students[] = new String [20];
         JOptionPane.showMessageDialog(null, students);
    }
}

//this is where Student Class is defined

class Student{
    //add variables, constructors and methods here
    String name = "";
    String height = "";
    int grades [] =new int [10];

  for(i = 0; i < grades.length; i++)
    {
        grades[i] = rand(60,99);
    }


    public Student(String n, String h, int g[])
    {
        name = n;
        height = h;
        grades = g;

    }

}

最佳答案

导致该特定错误的问题是您尝试运行 for 循环,但它不属于任何方法或构造函数。你必须首先涵盖它。另外,您需要在循环中声明 i 的类型,否则您也会收到不同的错误。

class Student{
    //add variables, constructors and methods here
    String name = "";
    String height = "";
    int grades [] =new int [10];

    public void initGrades()
    {
        for(int i = 0; i < grades.length; i++)
        {
            grades[i] = rand(60,99);
        }
    }


    public Student(String n, String h, int g[])
    {
        name = n;
        height = h;
        grades = g;
        initGrades();
    }

}

关于java - 如何消除错误 : illegal start of type in java?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35990836/

相关文章:

java - 从 Java 可见的 Scala 中的包私有(private)范围

java - 接受并返回对象的 REST 服务。客户端怎么写?

Java3d Mac OSX 新手安装指南

c - 在 C 中自动将值复制到指针

c - 将指针传递给数组并分配内存

arrays - 如何使用 Ruby 连接数组中的字符串

java - java中使用equalsIgnoreCase显示错误的方法

java - java中带定时器的单线程程序

c - char数组前面的&符号会影响scanf吗?合法吗?

javascript - 为什么 JSON.parse(['1234']) 返回 1234?