我正在嘗試使用JOptionPane顯示我的人員對象(名稱,年齡)。 (名稱和年齡是命令行參數中的字符串和整數)。但是,我收到以下錯誤:從類錯誤創建新對象Java
BasicClass.java:9: error: non-static variable this cannot be referenced from a static context
Person person1 = new Person(args[0], age1);
^
BasicClass.java:10: error: non-static variable this cannot be referenced from a static context
Person person2 = new Person(args[2], age2);
^
我是否正確初始化第一個Person對象到命令行輸入?
EDIT 對不起,我忘記了自己的代碼示例:
import javax.swing.JOptionPane;
public class BasicClass{
public static void main(String[] args){
Integer age1 = Integer.parseInt(args[1]);
Integer age2 = Integer.parseInt(args[3]);
// Create two Person Objects
Person person1 = new Person(args[0], age1);
Person person2 = new Person(args[2], age2);
// toString() method to display first & second Person Object
String firstOutput = person1.toString();
String secondOutput = person2.toString();
JOptionPane.showMessageDialog(null, firstOutput);
JOptionPane.showMessageDialog(null, secondOutput);
}
// Object
class Person{
// Data fields that will store each of the objects data
private String name;
private Integer age;
// Constructor
public Person(String n1, int a1){
name = n1;
age = a1;
}
public String toString(){
String output = name + " is" + age + " years old.";
return output;
}
}
}
在此處張貼您的代碼 –
如果沒有查看您的代碼,無法發表評論。發佈Person類和發生此錯誤的類。 – RaviH
讓Person類靜態 –