Coding | Mcqs | Multiple choice questions | Informative | Computer Science | Engineering | Aptitude | Quants | Verbal

INFEED

Define class Person Java


Define class Person

//Click on the Ads Shown in the blog

The program must accept the details of a person(name & age) based on the query Q as the input. The program must print the output based on the following conditions, 

-The default name of the person is "person and the age is 0.

-If the query is 1, then the program must print the default values of the name and age separated by a colon.

If the query is 2, then the program must print the given name and the default value of the age separated -If the query is 3, then the program must print the given name and age separated by a colon.

Note: The query value can be 1 or 2 or 3.


Example Input/Output 1:

Input:

1


Output:

person:0


Example Input/Output 2:

Input:

2

Rachel


Output:

Rachel:0


Example Input/Output 3:

Input:

3

Mambo

45


Output:

Mambo:45

//Click on the Ads Shown in the blog

Code Snippet:

import java.io.*;
import java.util.*;

class Person{

private String name;

private int age;

public Person()

{this.name="person";

this.age=0;

}

public Person(String name)

{this.name=name;

this.age=0;

}

public Person(String name,int age)

{this.name=name;

this.age=age;

}

@Override

public String toString()

{

return this.name+":"+this.age;

}

}

//Click on the Ads Shown in the blog

public class Hello {


    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        int query = Integer.parseInt(sc.nextLine().trim());

        Person p = null;

        if (query == 1) {

            p = new Person();

        } else if (query == 2) {

            String name = sc.nextLine();

            p = new Person(name);

        } else if (query == 3) {

            String name = sc.nextLine();

            int age = Integer.parseInt(sc.nextLine().trim());

            p = new Person(name, age);

        }

        System.out.println(p);

    } //end of main method

} //end of Hello class

Click on the Ads Shown in the blog

Post a Comment

Previous Post Next Post