In: Computer Science
10) Create a java program that will ask for name and age with method age where it will check the condition that id you are greater than 18 you can vote.
For the given program, a method checkAge() can be used to check eligibility to vote. The required program and corresponding output are as follows. The code is well commented for better understanding.
import java.util.Scanner;
public class Voting {
public static int checkAge(int a){//cheks for eligibility
int r;
if(a>18)//if age greater than 18
{
r=0;
}
else
{
r = (18 - a);//else returns difference in age
}
return r;
}
public static void main(String[] args) {
int vote;
Scanner scan = new Scanner(System.in);
System.out.println("Enter your Name:");
String name=scan.nextLine();//reads name
System.out.println("Enter your Age:");
int age = scan.nextInt();//reads age
vote=checkAge(age);//calls function to check age
System.out.println("Name:"+name);//displays name
if(vote==0){//checking return value
System.out.println("You are eligible to vote.");
}else{
System.out.println("Sorry, you can't vote now! You can vote after :"+ vote + " years");
}
}
}
Output: