Please can anyone tell me what the error is in the following piece of code?
Question is
Create a class person which has
A variable ‘name’ which stores the name of the person.
A constructor that takes a single argument that is used to initialize the name variable
A method getName() which displays the name.
A protected method setName() that takes one argument which is used to modify the name variable.
Create a subclass of the above class called student, which contains
A variable to store PRN of a student
A variable to store course the student belongs to
A method, which displays all the details of the student i.e, name, prn and course.
Program :
class Person
{
String name;
Person(String s)
{
name=s;
}
void getName()
{
System.out.println("Name is "+name);
}
void setName(String sa)
{
name=sa;
}
}
class subPerson extends Person
{
//String sa;
int Prn;
String course;
subPerson(String s,int P,String co)
{
name=s;
Prn=P;
course=co;
}
void displayal()
{
System.out.println("Name is ");
System.out.println("PRN is "+Prn);
System.out.println("course is "+course);
}
}
class Inher
{
public static void main(String args[])
{
int area,volumea;
subPerson h1 = new subPerson("Abhishek",20,"MBA");
h1.displayal();
}
}
Person's constructor takes a String. Since subPerson extends Person, its constructor will invoke a constructor of Person. By default it'll use the no-arg constructor, but since Person doesn't have one, it won't work.
Try changing subPerson's constructor to this:
subPerson(String s,int P,String co)
{
super(s);
Prn=P;
course=co;
}
I assume that compiles (I'm not going to check that), then the fundamental problem is that in the displayal() method, you don't actually print out the name...
System.out.println("Name is ");
should actually be something like
System.out.println("Name is " + name);
Aside from that, there are some problems with not following typcial java coding conventions. While the code may compile and do what is desired, most java guys will likely get hung up on "not following naming conventions" instead of trying to fix the problem because the code looks unusual.
I'd also recommend that you pay more attention to names. They matter a great deal and deserve careful thought.
"subPerson" as a class name leaves me quite cold. Aside from the poor camel case style, the assignment explicitly calls for a class Student. Why did you go with "subPerson"?
I would advise against the "displayal" (sic) method as well. The proper idiom is to override the toString() method in Object.
I'd write it like this:
/**
* Person
* User: Michael
* Date: Sep 27, 2009
* Time: 10:00:00 AM
*/
public class Person
{
private String name;
public static void main(String[] args)
{
Person s = new Student("Foo Bar", "35", "Intro To Java");
System.out.println(s);
}
public Person(String name)
{
if ((name == null) || (name.trim().length() == 0))
throw new IllegalArgumentException("name cannot be blank or null");
this.name = name;
}
public String getName()
{
return name;
}
public void setName(String name)
{
if ((name == null) || (name.trim().length() == 0))
throw new IllegalArgumentException("name cannot be blank or null");
this.name = name;
}
#Override
public String toString()
{
return "Person{" +
"name='" + name + '\'' +
'}';
}
}
class Student extends Person
{
private String prn;
private String course;
Student(String name, String prn, String course)
{
super(name);
this.prn = prn;
this.course = course;
}
#Override
public String toString()
{
return "Student{" +
"name='" + getName() + '\'' +
", prn='" + prn + '\'' +
", course='" + course + '\'' +
'}';
}
}
Related
I am working on my final project in a computer class and am trying to implement a basic if/else statement in a nested class but it is only opting to use the else case.
import java.util.Scanner;
public class CollegeApplication {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
//create object by default constructor
College c1 = new College();
//create object by overloaded constructor
College c2 = new College("Frostburg", "Frostburg", "MD", 5142);
College c3 = new College("UMBC", "Baltimore", "MD", 14000);
//set the information of object 1
c1.setName("Full Sail");
c1.setCity("Winter Park");
c1.setState("FL");
c1.setStudent_Body(19285);
System.out.println("Enter your states two-letter abbreviation");
String user_State = scan.nextLine();
c1.printCollege();
System.out.println();
c2.printCollege();
System.out.println();
c3.printCollege();
}
}
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
import java.util.Scanner;
public class College {
// private data members
private String name;
private String city;
private String state;
private int student_Body;
private String tuition;
private String user_State;
// default constructor which set the data member to default value
public College() {
this.name = "";
this.city = "";
this.state = "";
this.student_Body = 0;
this.tuition = "";
this.user_State = "";
}
// parameterized constructor
public College(String name, String city, String state, int student_Body) {
super();
this.name = name;
this.city = city;
this.state = state;
this.student_Body = student_Body;
}
// getter and setter
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public int getStudent_Body() {
return student_Body;
}
public void setStudent_Body(int student_Body) {
this.student_Body = student_Body;
}
// print college data
public void printCollege() {
System.out.println("Name of College: " + name);
System.out.println("City of Collge: " + city);
System.out.println("State of Collge: " + state);
System.out.println("Student Body Count: " + student_Body);
this.user_State = user_State;
if (state.equals(user_State)) {
this.tuition = "Eligible";
}
else {
this.tuition = "Ineligible";
}
System.out.println("In-State Tuition: " + tuition);
}
}
If anyone could help id be greatly appreciative in knowing how to alter the if statement to not only print ineligible
This question does not contain a question but I see the problem area.
Ask yourself why your College has both a state and a user_State. Why would this class have an aspect of itself be a user_State? There isn't even a getter and setter for it (as there shouldn't be).
public void printCollege() {
this.user_State = user_State;
if (state.equals(user_State)) {
this.tuition = "Eligible";
}
else {
this.tuition = "Ineligible";
}
System.out.println("In-State Tuition: " + tuition);
}
This function takes no input and gives no output, but has side-effects of printing something and modifying fields.
The only other time user_State is referenced in College is when it's set to the empty string.
this.user_State = "";
And that's only when a College object is constructed with the default constructor. If a College object is made using the argument constructor, user_State remains null.
Anyway, this method begins by setting this empty string (or null) to itself:
this.user_State = user_State;
So it's just going to be the empty string (or null).
Next it compares the strings state with the empty string or null in user_State.
if (state.equals(user_State)) {
state is not equal to the empty string nor null in any of your test cases, so it continues to the else clause:
else {
this.tuition = "Ineligible";
}
What you probably intend is for printCollege() to take the user_State variable you asked the user for. In which case it does not take 0 arguments, it takes 1 string argument.
public void printCollege(String userState) {
if (state.equals(userState)) {
this.tuition = "Eligible";
}
else {
this.tuition = "Ineligible";
}
System.out.println("In-State Tuition: " + tuition);
}
and the invocations of printCollege(String userState) should be done as appropriate, with the input you received from the user.
Please follow Java naming conventions in the future, something like user_State should just be userState.
there is no setter method for user_State instance variable
no parameter provided for initialization of user_State instance variable
so if condition fails as it considers user_State variable as instance variable it will always be "" in case of default constructor and "null" in case of parameterized constructor
either
provide parameter to printCollege() method according to #PatricChen
or
remove the statement this.user_State = user_State from
printCollege() and provide setter method for user_State variable and
a user_State parameter to parameterized constructor of College class
I have a Student class that contains an ArrayList of type Course, and Course is class with some fields like className, classTime, etc along with the appropriate getters and setters. Say I created an ArrayList of Course and have stored it into the Student class.
How can I for example print the className of a particular Course object (which is stored in an ArrayList stored in the Student class)?
So far I tried this, below is part of the code for class Student:
class Student {
ArrayList<Course> studentSchedule;
public ArrayList<Course> getStudentSchedule() {
return studentSchedule;
}
public void setStudentSchedule(ArrayList<Course> studentSchedule) {
this.studentSchedule = studentSchedule;
}
}
Then I have some code that created student1 of type Student and stored an ArrayList of Course into it.
Say I want to access the className in the first object in the ArrayList that's in student1. So far I have this and it works... is it fine?
ArrayList<Course> schedule = student1.getStudentSchedule();
System.out.print("\n course name at position 0 is " +
student1.getStudentScheduleClassName(0));
It feels weird to create another Arraylist just for this purpose... but then I thought since in line 1, schedule will only contain the addresses that point to the location and shouldn't take much space?
Is there a more appropriate way to do this?
Based on above discussion I tried to complete the solution for my reference.
import java.util.ArrayList;
import java.util.Iterator;
public class ListExample {
public static void main(String[] args) {
Student student1 = new Student();
ArrayList<Course> student1Schedule = new ArrayList<Course>();
student1Schedule.add(new Course("Computer Science", "Training Room"));
student1Schedule.add(new Course("Mobile App Development", "Training Room 2"));
student1.setStudentSchedule(student1Schedule);
// Prints only one course
System.out.println(" ** Course" + student1.getStudentSchedule().get(0).toString());
// Print all the courses attended by the student
ArrayList<Course> studentDetails = student1.getStudentSchedule();
Iterator<Course> studentIterator = studentDetails.iterator();
while (studentIterator.hasNext()) {
Course courseName = studentIterator.next();
System.out.println(courseName);
}
}
static class Student {
private ArrayList<Course> studentSchedule;
public ArrayList<Course> getStudentSchedule() {
return studentSchedule;
}
public void setStudentSchedule(ArrayList<Course> studentSchedule) {
this.studentSchedule = studentSchedule;
}
}
static class Course {
private String courseName;
private String className;
public Course (String courseName, String className){
this.className =className;
this.courseName = courseName;
}
public String getCourseName() {
return courseName;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public String toString (){
return "Course Name :" + this.courseName + "\n" + "Class Name : " + className + "\n";
}
}
}
public class Course{
private String className;
public String getClassName(){
return className;
}
public void setClassName(String c){
className =c;
}
}
So when you have this you can simply do
System.out.println(student1.getStudentSchedule().get(0).getClassName())
Make className into an instance variable of Course and have getter and setter methods within the Course for the class name. Then you will print out the class name.
You can access the first course's class name as:
System.out.print("\n course name at position 0 is " + schedule.get(0).getClassName());
since you've already defined getter/setter in the Course class as you mentioned.
Trying to print out age and name of an Object using "get" method. However, my get method return type is string:
public String displayProfile() {
System.out.print(getName() + getAge());
Hence the error:
This method must return a result of type String
Here is my main method: if user enters '2' from the "menu" where (2 == profile) the program should display user's name and age.
Side note: To select "friends" from menu, user will enter '3' (3 = friends).
public static void main(String[] args) {
// Initializing Objects
People zac = new People();
zac.setName("zac");
zac.setAge(18);
People lisa = new People();
lisa.setName("lisa");
lisa.setAge(19);
// Zac be-friend LISA
zac.addFriend("lisa");
openApp();
if(optionSelected == 3)
{
System.out.println(zac.getFriend());
else if (optionSelected == 2) {
System.out.println(zac.displayProfile());
}
}
}
Being new to programming, I want to develop good programming practices, hence with this in mind; how would you display age and name of different type [int = age and string = name] from one method like i.e. public String displayProfile() OR is this completely wrong? Then what are the alternatives?
Additionally:
My getName() method:
// GET NAME
public String getName() {
return this.name;
}
My setName() method:
// SET NAME
public void setName(String name) {
this.name = name;
}
My getAge() method:
// GET AGE
public int getAge() {
return this.age;
}
My setAge() method:
// SET AGE
public void setAge(int age) {
age = this.age;
}
You can use String.format() with format specifiers (%s, %d, %f...)
public static String displayProfile()
{
return String.format("%s %d", "StackOverflow", 6);
}
Note the return statement. It's totally different than System.out.print(...)
Also, the body of setAge() method, should look like:
this.age = age;
since you want to assign the age passed as parameter to the member this.age
My professor just went over mutable and immutable, and gave us this coding exercise to complete.
1) Create a Customer object called customer with initial values of 1 and "Cust1"
respectively.
2) Display the customer object to the screen using the toString() method.
3) Create a String object reference called name and assign to it the customer's name.
4) Assign the value "Bo Beep" to the object reference name.
5) Display the customer object to the screen using the toString() method.
The output should look like this.
Customer{id=1, name=Cust1}
Customer{id=1, name=Cust1}
I currently have 2 seperate classes, here they are. I'm not sure whether I'm doing it correctly, I think I have done the first 2 right, but I'm not sure about 3-5.
Any input is helpful, thanks!
Here's my main class,
package hw01;
public class Main {
static Customer customer = new Customer(1, "cust1");
static Customer name = new Customer(1, "Bo Peep");
public static void main(String[] args) {
System.out.println(customer);
System.out.print(customer);
}
}
And here's my Customer class.
package hw01;
public class Customer {
private int id;
private String name;
public Customer() {
}
public Customer(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
#Override
public String toString() {
return "Customer{" + "id=" + id + ", name=" + name + '}';
}
}
Sounds like for #3 it should be something like this:
String name = customer.getName();
and then #4 would be:
name = "Bo Peep";
The goal of the exercise I think is to demonstrate that even though name and customer.name reference the same String object, since a String is immutable when you set name = "Bo Peep"; you're not changing the actual String object but instead creating and referencing a new String object. If the String were mutable then printing the customer the 2nd time would display the name "Bo Peep".
I want to add a toString method in the Item class that returns the title of the item in there.
I have need make sure that the toString method in the DVD class calls the toString method in Item so that it can return a string that contains both the title and the director.
Item is the superclass and DVD is the subclass.
public class Item
{
private String title;
private int playingTime;
private boolean gotIt;
private String comment;
public Item(String theTitle, int time)
{
title = theTitle;
playingTime = time;
gotIt = false;
comment = "<no comment>";
}
// Getters and setters omitted
public void print()
{
System.out.print(title + " (" + playingTime + " mins)");
if(gotIt) {
System.out.println("*");
} else {
System.out.println();
}
System.out.println(" " + comment);
}
}
public class DVD extends Item
{
private String director;
public DVD(String theTitle, String theDirector, int time)
{
super(theTitle, time);
director = theDirector;
}
// Getters and setters omitted
public void print()
{
System.out.println(" director: " + director);
}
}
Item toString:
public String toString()
{
return title;
}
DVD toString:
public String toString()
{
return super.toString() + " director: " + director;
}
Also, I don't know what you're trying to do with this but I would put those print() methods in these classes.
You will be better of returning the string representation and printing it somewhere else (with this you can test this class without mocking System.out)
Cheers
A toString method is already defined in each Java class (it inherits the toString of Object). But it will return a practically meaningless value (AFAIR, the internal address/id of the instance within the JDK - I might be wrong).
What you need to do is to override that method and make it return a String that is the title of the Item. For the DVD class, you have to override toString and make it a string made up of the concatenation of the title and director.
For the Item class, your method should look something like this:
public String toString(){
return this.title;
}
You should be able to use the same idea to implement toString for DVD.