每当我使用 showMessage() 时,我都会得到空值;我相信这是因为我在方法结束时返回了 c 。有没有办法打印出 getName() 而不是在 main 方法中,就像 getName() 在 showMessage() 方法中一样。. 这是我的候选人类public class Candidate {private String name;private int votes;//default constructorpublic Candidate() {String name = "Not Available! ";int votes = 0; }//overloaded constructorpublic Candidate(String _name, int _votes){ name = _name; votes = _votes;}//getterpublic String getName(){return name;}public int getVotes(){return votes;}//setterpublic 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;}}
1 回答
慕斯709654
TA贡献1840条经验 获得超5个赞
只需更换
c1 = showMessage();
和,
showMessage(c1);
并修改方法showMessage如下
private static void showMessage(Candidate c ){
System.out.println(c.getName());
}
同样,您可以使用showMessage打印剩余对象的消息,例如
showMessage(c2);
showMessage(c3);
showMessage(c4);
添加回答
举报
0/150
提交
取消