我是编码新手,所以请多多包涵。在我的代码中,我的for循环(位于学生类中)收到一个非法的类型错误开始。如何解决此错误?
在我的for循环中,我想让我的数组等级具有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();
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句