如何打印getter String而不将null作为输出?

每当我使用 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;

}



}


不负相思意
浏览 183回答 1
1回答

慕斯709654

只需更换c1 = showMessage();和,showMessage(c1);并修改方法showMessage如下private static void showMessage(Candidate c ){        System.out.println(c.getName());}同样,您可以使用showMessage打印剩余对象的消息,例如showMessage(c2);showMessage(c3);showMessage(c4);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java