Java: beginner help getting variable - java

This is for a school project. I have built a simple class with 3 string variables and a constructor to fill these fields.
public class Names {
String firstName;
String middleName;
String lastName;
public Names(String name){
System.out.println("Passed name is: " + name);
}
public void setFirstName(String name){
firstName = name;
}
public void setMiddleName(String name){
middleName = name;
}
public void setLastName(String name){
lastName = name;
}
public static void main(String []args){
Names drew = new Names("Drew");
drew.setFirstName("Drew");
drew.setMiddleName("Leland");
drew.setLastName("Sommer");
System.out.println(drew.firstName + " " + drew.middleName + " " + drew.lastName);
}
public getFirstName(String name){
}
public getMiddleName(String name){
}
public getLastName(String name){
}}
At the bottom where it is getFirstName, getMiddleName, getLastName I want to be able to pass something like getFirstName(drew) and have it return drew.firstName?
I am very new to java FYI.

These are "getter" methods to return the values of instance fields. drew is your current Names instance here, therefore if you call these methods on this instance, you'll receive the values you've set with your "setter" methods. And since you're calling them on a specific instance, you don't need to pass it as a method argument. That is why these getter methods are normally parameterless.
They should look like this:
public String getFirstName() {
return firstName;
}
public String getMiddleName() {
return middleName;
}
public String getLastName() {
return lastName;
}
Please note that I've added the corresponding return type (String), because the data type of each instance field is String.
Your println call in the main method would then look like this:
System.out.println(drew.getFirstName() + " " + drew.getMiddleName() + " " + drew.getLastName());

public String getFirstName() {
return this.firstName;
}
This will return the firstName of the object you call it on.
You can call it like this:
System.out.println(drew.getFirstName() + " " + drew.middleName + " " + drew.lastName);
You can then do the same thing for getMiddleName and getLastName.

Your get methods will be called by an instance of your Names class. When you create an instance of the class and assign it a variable name, just use that variable name to call the method and it will return the name for that instance.
//Instantiate the Names class
Names drew = new Names("Drew");
//Call methods to set the names
drew.setFirstName("Drew");
drew.setMiddleName("John");
drew.setLastName("Smith");
//Call methods to get the names
drew.getFirstName(); //Returns "Drew"
drew.getMiddleName(); //Returns "John"
drew.getLastName(); //Returns "Smith"
And, like others suggested, your get / set methods should be like this:
public void setFirstName(String n){
firstName = n;
}
public String getFirstName(){
return firstName;
}

as you said, "I want to be able to pass something like getFirstName(drew) and have it return drew.firstName"
so the impl is simple,
public String getFirstName(Names other) {
return other.firstName;
}

Related

toString method is not showing anything when i run the code

toString method is not showing anything when I run the code:
public abstract class Employee {
private String firstName, lastname, socialSecurityNumber;
Employee(){
System.out.println("Employee Constructor called");
firstName="Tony";
lastname="Stark";
socialSecurityNumber="3000";
}
public String getFirstName(){
System.out.println(firstName);
return firstName;
}
public String getLastname(){
return lastname;
}
public String getSocialSecurityNumber(){
return socialSecurityNumber;
}
public String toString(){
getSocialSecurityNumber();
getLastname();
getFirstName();
return null;
}
}
//Main method:
public void ComissionEmployeeTest(){
Employee checkFirstly=new ComissionEmloyee();
checkFirstly.toString();
}
Your toString() is returns a null. You need to return a String instead.
Example
public String toString(){
return String.format("ssn %s firstname %s lastname %s",getSocialSecurityNumber() + getLastname() + getFirstName());
}
Your toString method should be
public String toString(){
return getSocialSecurityNumber()+
getLastname()+
getFirstName();
}
and you should nbe printing the same to see the value
System.out.println(checkFirstly);
When you call that toString(); method, you are getting always null as return.
With your method, doing System.out.println(e.toString()); is always the same as doing System.out.println(null);.
So you need to return the String, concatnated, composed with the variables. For example:
Modify the toString method like:
public String toString(){
//You can customize this as you wish
return "SN: " + getSocialSecurityNumber() + " Last name: " etLastname() + " First name: " +getFirstName();
}
and call it like:
Employee e = new Employee();
System.out.println(e.toString());
Edit
I see you have a output on the firstName getter, so doing new Empoyee().toString(); should at least output something.

Q: Player(class) java

Have to code a player class in java eclipse following these requirements
a) The Player class should have a default constructor and two custom constructors - one
that accepts a Name object, and another that accepts both a Name and PairOfDice object.
b) There should be get and set methods for its Name and a get method for PairOfDice. It
should have a method called rollDice and getDiceScore that both simply delegate to the
PairOfDice class, which already has this functionality. You should also have an
appropriate toString() method.
c) Add a further void method setFullPlayerName(String) that accepts a single String
argument (e.g. “Joe Bloggs”) and then uses this to set the first and family name
individually by extracting the relevant information and then calling the respective setter
methods of the Name class.
So far I have this
public class Player {
//Fields of the app
private String firstName;
private String lastName;
private Die red;
private Die blue;
//PlayerName and dice pair Default Constructor
public Player() {
firstName = "";
lastName = "";
red = new Die();
blue = new Die();
}
public Player(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public Player(String firstName, String lastName,Die red,Die blue) {
this.firstName = firstName;
this.lastName = lastName;
this.red = red;
this.blue = blue;
}
// Methods
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setlastName(String lastName) {
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public String getlastName() {
return lastName;
}
#Override
public String toString() {
return "PairOfDice:[red=" + red + ", blue=" + blue + "]";
}
public void rollDice() {
red.roll();
blue.roll();
}
public int getDiceScore() {
return red.getScore() + blue.getScore();
}
public Die getRed() {
return red;
}
public Die getBlue() {
return blue;
}
public String setFullName() {
if (firstName.equals("") && lastName.equals("")) {
return "";
} else {
return firstName + " " + lastName;
}
}
}
Is my code correct? if not what changes do i have to make to correct it
There are several problems:
Dice not Die: private Die red;
It's better to name your variable using a noun: private Dice redDice;
Should have a space after a comma: , Dice redDice, Dice blueDice
setFullName should accept 1 string and call setFirstName and setLastName to set the name
Example of implementation:
void setFullName(String fullName) {
/// split full name into lastName and firstName
setFirstName(firstName);
setLastName(lastName);
}
Everything seems fine, but I think you forgot to define the roll() function. Besides that, everything else seems fine :)
I see a couple of issues with this code:
a) The Player class should have a default constructor and two custom constructors - one that accepts a Name object, and another that accepts both a Name and PairOfDice object.
b) There should be get and set methods for its Name and a get method for PairOfDice. It should have a method called rollDice and getDiceScore that both simply delegate to the PairOfDice class, which already has this functionality. You should also have an appropriate toString() method.
If it's telling you that you need a Name object and a PairOfDice object, you can't just put in two Strings and two Dies and call that the same thing. You need to actually use the Name and PairOfDice classes.
c) Add a further void method setFullPlayerName(String) that accepts a single String argument (e.g. “Joe Bloggs”) and then uses this to set the first and family name individually by extracting the relevant information and then calling the respective setter methods of the Name class
Instead of setFullPlayerName, you made a method called setFullName that does not do what it's supposed to do. It's supposed to accept a String and return void, and instead it accepts no parameters and returns a String. It looks like a getter instead of a setter.
Let's get this straight: This portion of the code:
public String setFullName() {
if (firstName.equals("") && lastName.equals("")) {
return "";
} else {
return firstName + " " + lastName;
}
}
it's misleading due to the fact that the method name it's saying that it's setting the name, BUT you're returning the name instead
So change it to this:
public void setFullPlayerName(String name) {
String[] splitted = name.split(" ");
firstname = splitted[0];
lastname = splitted[1]
}
And now it's unnecessary to add the method setFullPlayerName
BUT I see that you may need a method to return a full name, so:
public String getFullPlayerName() {
return firstname + " " + lastname;
}
Hopefully that'll resolve your issue :D

Java code output is weird? [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed last month.
I do not understand why my output is not what I expected, instead of showing the persons information, the output displays: examples.Examples#15db9742
Am I doing something wrong in my code?
package examples;
public class Examples {
String name;
int age;
char gender;
public Examples(String name, int age, char gender){
this.name = name;
this.age = age;
this.gender = gender;
}
public static void main(String[] args) {
Examples[] person = new Examples[10];
person[0] = new Examples("Doe",25,'m');
System.out.println(person[0]);
}
}
Add a toString() method to your class:
public class Examples {
String name;
int age;
char gender;
public Examples(String name, int age, char gender){
this.name = name;
this.age = age;
this.gender = gender;
}
#Override
public String toString() {
StringBuilder result = new StringBuilder();
result.append(this.name + " ");
result.append(this.age + " ");
result.append(this.gender + " ");
return result.toString();
}
public static void main(String[] args) {
Examples[] person = new Examples[10];
person[0] = new Examples("Doe",25,'m');
System.out.println(person[0]);
}
}
When you say
System.out.println(person[0]);
java doesn't automatically know what you want printed out. To tell it, you write a method in your Examples class called toString() which will return a string containing the info you want. Something like:
#Override
public String toString() {
return "Name: " + name +
" Age: " + String.valueOf(this.age) +
" Gender: " + String.valueOf(this.gender);
}
Java has no way of knowing what you want it to print. By default, the toString() method is called when you use System.out.println() with an object.
Your Examples class should have its own toString() method so you can decide what to print. The default toString() returns a representation of the object in memory.
For example, to print out the object's name:
package examples;
public class Examples {
...
#Override
public String toString() {
return name;
}
}
Your output is right, when you print an object the method toString() of the object is called; by default it returns what you see (the class and a memory direction).
Override the method toString() of the class to make him return a descriptive String. E.g.:
public class Examples {
// The same ...
public String toString(){
return "My name is " + name + " and I have " + age + " years."
}
// The same ...
}
If you do that you will get a more descriptive String when calling toString() and so when printing an object of class Examples.
New output is
My name is Dow and I have 25 years.
person is an array of type Examples, so by acessing person[0] you are telling it to print an Examples instance. Since the Examples class does not implement an toString() method it will call the parent Object.toString() method that produces the output you are seeing.
Add the following method to your Examples class
public String toString() {
return "[name="+this.name+", age="+this.age+", gender="+this.gender+"]";
}
You have explicitly to create a method which outputs the persons data or override the toString() method to do the same thing:
public class Person
{
String name;
int age;
char gender;
public Person(String name, int age, char gender)
{
this.name = name;
this.age = age;
this.gender = gender;
}
//Override the toString() method
//is a usual programming technique
//to output the contents of an object
public String toString()
{
return "Name: " + this.name + "\nAge: " + this.age + "\nGender: "
+ this.gender;
}
//You can also write something like this
public void showInfo()
{
System.out.printf("Persons Info:\n\nName: %s\nAge: %s\nGender: %s", this.name, this.age, this.gender);
}
public static void main(String[] args)
{
Person p = new Person("bad_alloc", 97, 'm');
//System.out.println("Persons info:\n" + p.toString());
//If you want directly to "output the object" you have to override the toString() method anyway:
//System.out.println(p);//"Outputting the object", this is possible because I have overridden the toString() method
p.showInfo();
}
}

Final print statement returning null (java)

I have a basic name application that is taking in user data from the main class, splits the data in the parser class and then tries to assign everything in the final class and print it out in the toString method. I know the main class and the parser are working fine. I have verified in the parser class that the data DOES split properly and also sends the data through the object I made to the final class to assign it all. However, my final code is returning null..
MAIN CLASS
import java.util.Scanner;
public class MainClass {
public static void main (String[]args)
{
Scanner input = new Scanner(System.in); //create scanner object to gather name information
String fullName = null; //set the predefined value for the users name to null
nameParse splitInformation = new nameParse(); //method build to split the name into different sections
SecondClass access = new SecondClass(); //class built to output the different name data
System.out.println("What is your name?");
fullName = input.nextLine(); //store the users name and pass it into the data parser
splitInformation.parseNameInformation(fullName); //name parsing parameters built
System.out.println(access.toString());
}
}
Data Parser Class
public class nameParse {
private String firstName;
private String middleName;
private String lastName;
public nameParse()
{
firstName = "initial";
middleName = "initial";
lastName = "initial";
}
public void parseNameInformation(String inputInfo)
{
//Create an array to store the data and split it into multiple sectors
String nameInformation[] = inputInfo.split("\\s");
firstName = nameInformation[0];
middleName = nameInformation[1];
lastName = nameInformation[2];
//System.out.println(firstName + " " + middleName + " " + lastName);
SecondClass sendData = new SecondClass();
sendData.setFirstName(firstName);
sendData.setMiddleName(middleName);
sendData.setLastName(lastName);
}
}
Final Class
__
public class SecondClass {
private String firstName;
private String middleName;
private String lastName;
/*public String GFN()
{
return firstName;
}
public String GMN()
{
return middleName;
}
public String GLN()
{
return lastName;
}*/
public String setFirstName(String yourFirstName)
{
firstName = yourFirstName;
return this.firstName;
}
public String setMiddleName(String yourMiddleName)
{
middleName = yourMiddleName;
return this.middleName;
}
public String setLastName(String yourLastName)
{
lastName = yourLastName;
return this.lastName;
}
public String getFN()
{
return firstName;
}
public String toString()
{
String printNameInfo = "\nYour First Name:\t" + getFN();
return printNameInfo;
}
}
You never set any of your SecondClass object's (called "access") fields, so of course they'll all be null.
So in short, your code creates a nameParse object, gets information from the user, but does nothing with that information. You create a SecondClass object called access, put no data into it, and so should expect no valid data in it when you try to print it out. Solution: put information into your SecondClass object first. Call its setter methods:
// be sure to call the setter methods before trying to print anything out:
access.setSomething(something);
access.setSomethingElse(somethingElse);
Edit
You state:
I thought I set the data using the sendData.setFirstname(...) etc?
In the parseNameInformation method you create a new SecondClass object and you do set the fields of this object, but this object is completely distinct from the one in your main method whose fields are still null. To solve this, give parseNameInformation a method parameter and pass in your main method's SecondClass object into it and set its methods. You'll have to create the SecondClass object before calling the method of course.
i.e.,
public void parseNameInformation(String inputInfo, SecondClass sendData)
{
//Create an array to store the data and split it into multiple sectors
String nameInformation[] = inputInfo.split("\\s");
firstName = nameInformation[0];
middleName = nameInformation[1];
lastName = nameInformation[2];
//System.out.println(firstName + " " + middleName + " " + lastName);
// SecondClass sendData = new SecondClass(); // !!! get rid of this
sendData.setFirstName(firstName);
sendData.setMiddleName(middleName);
sendData.setLastName(lastName);
}

How can I print from this object? Java

I need to print the first name, last name, and salary from two employee objects but I keep getting a cannot find symbol error. What would I do to fix this?
Here is the constructor class:
public class Employee
{
private String firstName;
private String lastName;
private double monthlySalary;
public Employee( String firstName1, String lastName1, double monthlySalary1) {
setfirstName(firstName1);
setlastName(lastName1);
setmonthlySalary(monthlySalary1);
}
String getfirstName() {
return firstName;
}
String getlastName() {
return lastName;
}
double getmonthlySalary() {
return monthlySalary;
}
public void setfirstName (String firstName1) {
firstName = firstName1;
}
public void setlastName (String lastName1) {
lastName = lastName1;
}
public void setmonthlySalary (double monthlySalary1) {
monthlySalary = ( monthlySalary1 >= 0 ? monthlySalary1 : 0);
}
}
And here is what I have so far to print the objects:
public class EmployeeTest {
public static void main(String[] args) {
Employee a = new Employee("John", "Smith", 10000);
Employee b = new Employee("Jane", "Smith", 11000);
System.out.print(a.firstName1);
}
}
I need to be able to have it print out something along the lines of "Name: Salary:" But I am clueless as to how to make this work. Any help would be greatly appreciated.
In your employee class, you need to override the toString() method.
You can try something like:
#Override
public String toString()
{
System.out.println("Name: "+name+"Salary: "+salary);
}
Then for each of your employees, when you want to print them, just call
System.out.println(employee);
You cant print out firstName (or firstName1, because that doesnt exist in your class), because its marked as private. You should do something like this:
System.out.print(a.getfirstName())
firstName is private, which means that it cannot be seen outside of the object/class it resides in. I suggest you try overriding the toString() method on your Employee class. That method would have access to all the private members of Employee.
Alternately, you could use getfirstName() to return the first name.
Also, this may be a typo, but there is no firstName1 in Employee - it is firstName.

Categories

Resources