Hello I'm new to Java. I'm trying to create a object and pass name through it. I don't have a clue what I'm doing wrong?.
public class Employee
{
private String name, number;
private String date;
public Employee()
{
name= "";
number = "";
date = "";
}
public Employee(String name, String number, String date)
{
setName(name);
setNumber(number);
setDate(date);
}
public void setName(String n)
{
name = n;
}
public void setNumber(String n)
{
number = n;
// you can check the format here for correctness
}
public void setDate(String d)
{
date = d;
}
public String getName()
{
return name;
}
public String getNumber()
{
return number;
}
public String getDate()
{
return date;
}
}
import java.util.Scanner;
public class TeamLeadDemo
{
public static void main(String[] args)
{
String name;
// create scanner object
Scanner keyboard = new Scanner(System.in);
// inputting data
System.out.println("Enter Name:");
name = keyboard.nextLine();
// instantiating object, HERE IS THE PROBLEM
Employee thename = new Employee(name);
// outputting data
System.out.println("Employee Name:"+thename.getName());
System.out.println("Employee Details:\n" + thename);
}
}// Function definition
What should i do??
Hey fellow newbie programmer!
Take a look at how you initialize your object:
Employee thename = new Employee(name);
Since you only give it the String name as a parameter, Java cannot initialize your Employee object because it does not have a single argument constructor!
Here are your constructors method signatures:
public Employee()
public Employee(String name, String number, String date)
One takes no arguments, and the other takes 3 arguments.
If you look at the way you initialize it, you only pass 1 argument!
You would need to create a new Constructor that has a single argument in order for your code to work. Or easier yet, you could just pass in "", "" for your number and date string values.
More experienced programmers please do not hesitate to correct my programming semantics if they are wrong. I feel like I'm using words that I do not fully understand.
You need a constructor that receives only the name that you are passing:
public Employee(String name) {
this.name = name;
this.number = "";
this.date = "";
}
Currently you only have one default constructor and one that receives all three properties.
Your Employee class has two constructors: one taking zero arguments and one taking three arguments. Yet you're attempting to construct it with one argument. That wouldn't compile.
There are two possible solutions:
Add another constructor taking one argument.
public Employee(String name) {
this.name = name;
}
Use the constructor taking three arguments and pass null through.
Employee employee = new Employee(name, null, null);
Unrelated to the concrete problem, setting values to empty strings in the default constructor and calling the setters in the second constructors is not a nice practice. In the first, just do nothing, keep them default null. In the second constructor, you should prefer setting the property directly instead of calling the setter.
You need to pass in the number and date to the constructor as well. Try:
Employee thename = new Employee(name, "", "");
Employee thename = new Employee(name);
You have no constructor that takes only one String
If you have some very very strong reasons not to use Employee thename = new Employee(name, "", "");, you may try "varargs"
As :
public class Employee {
String fname="";
String lname="";
public Emp(String... attrs) {
if ( attrs.length > 1 ) {
fname = attrs[0];
lname = attrs[1];
}else if(attrs.length == 1) {
fname = attrs[0];
}
}
public String toString() {
return fname + " " + lname;
}
public static void main(String[] args){
Employee e1 = new Employee ("Test");
Employee e2 = new Employee ("Test" ,"case");
System.out.println(e1);
System.out.println(e2);
}
}
Caution : this is just to answer your question- Think before using in real world situations. Not from design/ best approach perspective. But it is different and caters to your question though ;-)
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
The values I am supposed to pass in:
Name and family should be saved for all instruments
We need to specify whether a strings instrument uses a bow
When I run my code it gives me the error: "constructor Strings in class Strings cannot be applied to given types;"
public class InstrumentTester
{
public static void main(String[] args)
{
/**
* Don't Change This Tester Class!
*
* When you are finished, this should run without error.
*/
Wind tuba = new Wind("Tuba", "Brass", false);
Wind clarinet = new Wind("Clarinet", "Woodwind", true);
Strings violin = new Strings("Violin", true);
Strings harp = new Strings("Harp", false);
System.out.println(tuba);
System.out.println(clarinet);
System.out.println(violin);
System.out.println(harp);
}
}
public class Instrument
{
private String name;
private String family;
public Instrument(String name, String family)
{
this.name = name;
this.family = family;
}
public String getName()
{
return name;
}
public String getFamily()
{
return family;
}
public void setName(String name)
{
this.name = name;
}
public void setFamily(String family)
{
this.family = family;
}
}
public class Strings extends Instrument
{
private boolean useBow;
public Strings(String name, String family, boolean useBow)
{
super(name, family);
this.useBow = useBow;
}
public boolean getUseBow()
{
return useBow;
}
public void setUseBow(boolean useBow)
{
this.useBow = useBow;
}
}
How do I pass in the parameter family if it doesn't take it?
Strings violin = new Strings("Violin", true);
Strings harp = new Strings("Harp", false);
The violin and harp don't get passed a family name when they're created, so the Strings constructor mustn't expect one as an argument.
public Strings(String name, boolean useBow)
What do you pass to super(), then? If all strings belong to the same family then you can hard code the value. Perhaps just "String":
public Strings(String name, boolean useBow)
{
super(name, "String");
this.useBow = useBow;
}
you define strings as one single constructor
public Strings(String name, String family, boolean useBow)
but you try to use it as a different parameters:
Strings violin = new Strings("Violin", true);
either you need to define a second constructor or use the one you created
How do I pass in the parameter family if it doesn't take it?
This sounds like as if you are passing in the family but the class doesn't take it. But the truth is, your class is taking an extra family parameter that is not passed.
Given the comments at the start of main, my interpretation is that you are supposed to give all Strings a family of "Strings". As you can see from the usage in Main, only 2 arguments are passed to the constructor, which means the Strings constructor is not supposed to accept a family parameter.
Therefore, the constructor should be like this:
public Strings(String name, boolean useBow)
{
super(name, "Strings"); // note that I replaced family with "Strings"
this.useBow = useBow;
}
Probably a pretty noob question, but I cant figure it out. I have a class Person to store a name that is input from the keyboard
public class Person {
private String firstName;
private String lastName;
public Person()
{
firstName = "";
lastName = "";
}
public Person(String first, String last)
{
setName(first, last);
}
public String toString()
{
return(firstName + " " + lastName);
}
public void setName(String first, String last)
{
firstName = first;
lastName = last;
}
public String getFirstName()
{
return firstName;
}
public String getLastName()
{
return lastName;
}
}
I am trying to call the toString method in a subclass called Patient
public class Patient extends Person {
private int patientID, patientAge;
public Patient()
{
patientID = 0; //for a different part of the class that works
patientAge = 0;
}
#Override
public String toString()
{
return ("Patient Name: "+super.toString());
}
}
I cannot get it to output the name in main when I call the toString method from the Patient class, but when I tested it, it output the name when I call the toString method from the Person class.
The method call in main looks like Patient pnt = new Patient(); System.out.print(Pnt.toString());
it prints out in the console "Patient Name: ". Any feedback on what I am doing wrong or ideas on how to get it to work
Here:
public Person()
{
firstName = "";
lastName = "";
}
Your subclass is missing a reasonable call to a super class constructor. So when you instantiate your Patient objects, the above constructor is used, and all patients end up with "" as first and last name!
When you create a Patient, then a patient should have a name, too! But your constructor in Patient only sets the Patient related fields. And implicitly, the default super constructor is called. Therefore the Person fields are all set to be empty strings!
A much better approach would look like this:
class Person {
private final String firstName;
... lastName
public Person(String firstName, String lastName) {
this.firstName = firstName;
...
and then
class Patient extends Person {
private final int patientID;
public Patient(int patientID, String firstName, String lastName) {
super(firstName, lastName);
this.patientID = patientID;
)
Why is that better: names and IDs don't change (normally). There is no point in having getters for them. You create your object once, and then that data is fixed! There is also no point in having that default constructor in Person. A person with empty names doesn't make sense. Thus: don't create a class that allows you to create "invalid" objects. Your classes model reality. There are no real people without names!
And one other hint: use #Override when overriding methods, so that the compiler can tell you when you get something wrong!
if the problem is to output the name in main when you call the toString method from the Patient class, I think the code bellow will help you.
have you tried to construct the Patient object like this?
public static void main(String[] args) {
Patient p = new Patient();
System.out.println(p.toString());
}
Actually I do not see problem in your code.
Person person = new Person();
person.setName("aa", "bb");
System.out.println(person); // aa bb
Patient patient = new Patient();
patient.setName("cc", "dd");
System.out.println(patient); // Patient Name: cc dd
I think that you set name wrong pr use not correct reference. Check it.
You don't have any constructor for your PATIENT subclass. You don't set any firstName or lastName to any patient.
To keep familiar constructor as you used in your parent class, tru to use:
public Patient() {
super("default_firstName", "default_lastName");
this.patientID = 0;
this.patientAge = 0;
}
public Patient(String firstName, String lastName, int patientAge) {
super(firstName, lastName);
this.patientID = 0; //can be implemented some method for automatically setting numbers
this.patientAge = patientAge;
}
This way you always get firstName and lastName even if constructor will be called empty.
According to you toString method, it's correct and it call super class method:
#Override
public String toString()
{
return("Patient name is "+super.toString());
}
But notice that you return STRING value so to make it visible on the screen remember to use:
System.out.println(patient.toString());
Then it will be visible :)
I have added some comments and code in your Person class that should fix your issues.
public class Person {
private String firstName; //store the first name
private String lastName; //sore the last name
//initialize firstName and lastName to an empty string
public Person() {
firstName = "";
lastName = "";
}
//set firstname and lastname according to the parameters.
public Person(String first, String last) {
//setName(first, last); remove this crap.
// Use the contructor properly when initialize your person object. Like this:
this.firstName = first;
this.lastName = last;
}
//method to output the first name and last name
#Override
public String toString() {
return (firstName + " " + lastName);
}
//method to set firstName and lastName according to the paramters
public void setName(String first, String last) {
//
firstName = first;
lastName = last;
}
}
I have cut out the code to shorten the page but I'm asking how do I change personInterests into its own class. Apologies for the vague question but essentially I want to change personInterests in my Person class to a class where personInterests has multiple variables.
import java.util.ArrayList;
import java.util.*;
public class Person{
private String personName;
private String[] personInterests = new String[3];
public Person(String personName, String[] personInterests){
this.personName = personName;
this.personInterests = personInterests;
}
public void setInterests(String[] personInterests){
this.personInterests = personInterests;
}
public String[] getInterests(){
return personInterests;
}
public String getName(){
return personName;
}
public String toString(){
String result = getName() + " ";
for (String interests : personInterests) {
result += interests + " ";
}
return result;
}
}
This was my idea of how it would work just not sure how I would use this class and call it later on.
import java.util.ArrayList;
import java.util.*;
public class Interests {
private int interestDangerRating;
private String interestName;
private ArrayList<Interests> interestsList = new ArrayList<>();
public Interests (int interestDangerRating ,String interestName){
this.interestDangerRating = interestDangerRating;
this.interestName = interestName;
}
public void addInterests(Interests p){
interestsList.add(p);
}
Interests getInterests(int i){
return interestsList.get(i);
}
}
Any help is appreciated, as I said this code has mostly been taken out and this was an old project already completed just wanted to see if I could change some of the features.
OK so here's what I would do to clean this up for you and make it work. Firstly, think about what you are trying to do. You want to create a Person who has multiple Interests, right? So the Interest class, going by your above example, can be changed to be a typical Java object class as follows:
public class Interest {
private int dangerRating;
private String name;
public Interest (int dangerRating, String name) {
this.dangerRating = dangerRating;
this.name = name;
}
public int getDangerRating() {
return dangerRating;
}
public String getName() {
return name;
}
}
So now we've an Interest class set up where you can set a name for your interest and a danger rating. What we need to do, now, is edit your Person class so as you can store a list of interests for each Person you create.
import java.util.ArrayList;
public class Person{
private String name;
private ArrayList<Interest> interests = new ArrayList<Interest>();
public Person(String name, ArrayList<Interest> interests) {
this.name = name;
this.interests = interests;
}
public void addInterest(Interest newInterest) {
interests.add(newInterest);
}
public Interest getInterest(int indexOfInterest) {
return interests.get(indexOfInterest);
}
public ArrayList<Interest> getInterests() {
return interests;
}
public String getName() {
return name;
}
public String toString() {
String result = getName() + " ";
for(Interest interest : interests) {
result += interest.getName() + "(" + interest.getDangerRating() + ")" + " ";
}
return result.trim();
}
}
This allows you to set an initial list of all interests for your new Person and, from there, you can add new interests, get all interests or get any individual interest.
Hope this helps to clarify for you how this should all fit together!
So now it's time to instantiate everything. Lets create some Interestobjects which we will use:
Interest golf = new Interest(1, "golf");
Interest swimming = new Interest(3, "swimming");
Now lets assume we want two people called John and Mary. John likes golf and swimming while Mary only likes swimming. We'd then create their list of Interest as follows:
ArrayList<Interest> johnsInterests = new ArrayList<Interest>();
johnsInterests.add(golf);
johnsInterests.add(swimming);
ArrayList<Interest> marysInterests = new ArrayList<Interest>();
marysInterests.add(swimming);
And finally, we'd then create our two Person objects which will include the persons name and interests list.
Person john = new Person("John", johnsInterests);
Person mary = new Person("Mary", marysInterests);
And voila!
First, make an Interestclass:
public class Interest {
private int interestDangerRating;
private String interestName;
// .. getters and setters
}
then in the Personclass get rid of private String[] personInterests = new String[3];
and replace it by:
private ArrayList<Interest> interestsList = new ArrayList<>();
You're getting there with the logic of your Interests class, but it needs a few changes
import java.util.ArrayList;
import java.util.*;
public class Interests {
private int interestDangerRating;
// Is this a unique name for the entire class? If yes then no worries, but if not
// then its not needed, you've already got a list of interest names below
private String interestName;
// Change the array list to hold Strings, it's a list of words
private ArrayList<String> interestsList = new ArrayList<>();
public Interests (int interestDangerRating ,String interestName){
this.interestDangerRating = interestDangerRating;
this.interestName = interestName;
}
public void addInterest(String p){ // Again, change this to String
interestsList.add(p);
}
String getInterest(int i){ // Change this to return a String, since we changed the ArrayList above
return interestsList.get(i);
}
}
There's alot more you need to think about with this class too. How do you know how many interests are in the list, should there be a length variable? Or what about a method that returns the entire list of interests rather than just 1?
Also, there's only one interestDangerRating being set in this class; if each interest has a different danger rating, should't you be adding a danger rating for every interest?
In terms of accessing your new class, you'll need to create a class in your code by:
Interests variableName = new Interests(1, "football");
I have randomly chosen '1' and 'football' above, since they are in your Interest class' constructor. The way your class is built, you cannot use it without providing an int and a String when the object is made
Finally, to call methods on your class, you use the variable created above to call its methods:
variableName.addInterest("basketball");
String interest = variableName.getInterest(1);
If you're struggling, I recommend looking at a simple java tutorial online. instatiating java classes and calling their methods like this are fundamental concepts in Java :)
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".