每当我使用 showMessage() 时,我都会得到空值;我相信这是因为我在方法结束时返回了 c 。有没有办法打印出 getName() 而不是在 main 方法中,就像 getName() 在 showMessage() 方法中一样。. 这是我的候选人类
public class Candidate {
private String name;
private int votes;
//default constructor
public Candidate() {
String name = "Not Available! ";
int votes = 0;
}
//overloaded constructor
public Candidate(String _name, int _votes){
name = _name;
votes = _votes;
}
//getter
public String getName(){return name;}
public int getVotes(){return votes;}
//setter
public void incrementVote(){
votes = votes + 1;
}
public void setName(String _name){
name =_name;
}
public void print(){
System.out.println("To vote for " + name);
}
}
这是我的主要
import java.util.*;
public class Election {
public static void main(String args[]){
System.out.println("Welcome to the polls! ");
Candidate c1 = new Candidate();
Candidate c2 = new Candidate();
Candidate c3 = new Candidate();
Candidate c4 = new Candidate();
c1 = inputCandidate();
c2 = inputCandidate();
c3 = inputCandidate();
c4 = inputCandidate();
c1 = showMessage();
}
private static Candidate inputCandidate(){
Scanner sc = new Scanner(System.in);
String inputN;
Candidate c = new Candidate();
System.out.println("Enter candidate");
inputN = sc.nextLine();
c.setName(inputN);
return c;
}
private static Candidate showMessage(){
Candidate c = new Candidate();
System.out.println(c.getName());
return c;
}
}
慕斯709654
相关分类