I get the null value whenever I use showMessage(); I believe that it is because of me returning c at the end of the method. Are there any way to print out getName() without it being in main method, as in getName() being in the showMessage() method. . Here is my Candidate class
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);
}
}
Here is my main
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;
}
}
just replace
c1 = showMessage();
with,
showMessage(c1);
and modify method showMessage
like the following
private static void showMessage(Candidate c ){
System.out.println(c.getName());
}
so similarly, you can use showMessage
to print messages for remaining objects like
showMessage(c2);
showMessage(c3);
showMessage(c4);