我正在尝试创建一个Node类,我希望默认为全0和null然后当我用构造函数调用节点类时我想设置它们。现在我已经设定了代码,我一直在努力 symbol:方法Node(int,int,java.lang.String) location:Node类型的变量n1 我不明白我的默认构造函数有什么问题,因为它只有在我删除它时才会起作用。
class Node{
private int ticks;
private int jobId;
private String name;
private Node next;
public Node(){
next = null;
ticks = 0;
jobId = 0;
name = " ";
}
public Node(int t,int j, String name){
ticks = t;
jobId = j;
name = name;
}
//sets next to node
public void setNext(Node next){
next = next ;
}
}//end class node
MAIN ---------------------------------------------- -----------
public class lab3{
public static void main(String[] args) throws Exception{
//Open File
File file = new File("p3.dat");
Scanner in = new Scanner(file);
int jobId = storeJobIdNum(in);
int ticks = storeTicks(in);
String name = storeName(in);
Node n1 = new Node();
n1.Node(ticks,jobId,name);
jobId = storeJobIdNum(in);
ticks = storeTicks(in);
name = storeName(in);
// String line = in.nextLine();
// String name = line;
//System.out.println(jobId+" "+num+" "+numTicks);
// n1.setNode(,,);
}//end main
public static String storeName(Scanner in){
String name = in.next();
System.out.println(name);
return name;
}
public static int storeJobIdNum(Scanner in){
int num = in.nextInt();
System.out.println(num);
return num;
}
public static int storeTicks(Scanner in){
int num = in.nextInt();
System.out.println(num);
return num;
}
}//end class
p3.dat看起来像==> 1 4名 并且有几行不同。
答案 0 :(得分:3)
创建对象后,您将无法使用它调用另一个构造函数。相反,创建一个负责更改字段的方法。
将此作为方法调用来设置属性:
Node n1 = new Node();
n1.set(ticks,jobId,name);
然后在Node中,使用它而不是另一个构造函数:
public void set(int t,int j, String name){
this.ticks = t;
this.jobId = j;
this.name = name;
}
您通常会听到这些被称为" setter"方法。