Answer to Question #196395 in Java | JSP | JSF for mechanix

Question #196395

Write a Java code Using Arraylist and Inheritance.


Input Sample

Enter number of presidents: 5

Enter class president id: 10

Enter class president id: 20

Enter class president id: 30

Enter class president id: 40

Enter class president id: 50


Output :

power on class 10

power on class 20

power on class 30

power on class 40

power on class 50

power on school

Best president id: 10


or


Input

Enter number of presidents: 2

Enter class president id: 45

Enter class president id: 23


output :


power on class 45

power on class 23

power on school

Best president id: 45


or


Input:


Enter number of presidents: 0


output:

power on school


1
Expert's answer
2021-05-21T16:50:24-0400
package freelance;


import java.util.ArrayList;
import java.util.Scanner;


public class ClassPresident {
	private int id;
	private static ArrayList<ClassPresident> ids = new ArrayList<>();
	private static SchoolPresident schoolPresident;


	public ClassPresident(int i) {
		id = i;
	}


	public static void addPresidentId(int id) {
		ClassPresident c = new ClassPresident(id);
		if (ids.isEmpty())
			schoolPresident = new SchoolPresident(c);
		ids.add(new ClassPresident(id));
	}


	public static void showPresidents() {
		int nmb = 0, n = 0;
		try (Scanner scanner = new Scanner(System.in)) {


			System.out.print("Enter number of presidents: ");
			if (scanner.hasNextInt())
				nmb = scanner.nextInt();
			for (int i = 0; i < nmb; i++) {
				System.out.print("Enter class president id ");
				if (scanner.hasNextInt()) {
					n = scanner.nextInt();
					addPresidentId(n);
				}
			}
			for (int i = 0; i < ids.size(); i++)
				System.out.println("power on class " + ids.get(i).id);
			System.out.println("power on school ");
			if (schoolPresident != null)
				System.out.println("Best president id: " + schoolPresident.bestId);
		}
	}


	static class SchoolPresident extends ClassPresident {
		int bestId;


		SchoolPresident(ClassPresident c) {
			super(c.id);
			bestId = c.id;
		}


	}


	public static void main(String args[]) {
		showPresidents();
	}
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS