Final print statement returning null (java) - 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);
}

Related

Printing elements of list of objects [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 3 years ago.
//contacts class
package com.company;
public class Contacts {
private String name;
private String number;
public Contacts(String name, String number) {
this.name = name;
this.number = number;
}
public String getName() {
return name;
}
public String getNumber() {
return number;
}
}
//class Phone
package com.company;
import java.rmi.StubNotFoundException;
import java.util.ArrayList;
public class Phone {
private ArrayList<Contacts> contacts1 = new ArrayList<Contacts>();
public void addContact(String name, String numbers) {
Contacts contacts = new Contacts(name, numbers);
contacts1.add(contacts);
}
public void printContacts() {
for (int i = 0; i < contacts1.size(); i++) {
System.out.println(contacts1.); // >>> how to print elements (name and phone number)
}
}
}
Here I tried to print a list of contacts including name and phone number but could not handle how to iterate over a list of objects. How can I print name and phoneNumber using printContacts() method in Phone class?
Thanks
You would do:
System.out.println(contacts1.get(i));
but that would just give Contacts#somenumber, so you will need to add a toString() method to the Contacts class.
In the contacts class, add a function that looks like this:
#Override
public String toString() {
return name + ": " + number;
}
Override toString method in your class Contacts to return a string representation of your class object (for e.g. json string). System.out.println prints string returned by this method.
public class Contacts {
private String name;
private String number;
...
#Override
public String toString() {
return "{\"name\": \"" + name + "\", \"number\": \"" + number + "\"}";
}
}
P.S. If you are using one the java IDEs, check out the implementation of println method in file PrintStream.java in java source code. Java IDEs provides this feature of code navigation in your project by which you can actually navigate through source code of Java itself.

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

how can I return a String?

package book1;
import java.util.ArrayList;
public abstract class Book {
public String Book (String name, String ref_num, int owned_copies, int loaned_copies ){
return;
}
}
class Fiction extends Book{
public Fiction(String name, String ref_num, int owned_copies, String author) {
}
}
at the moment when i input values into the variable arguments and call them with this :
public static class BookTest {
public static void main(String[] args) {
ArrayList<Book> library = new ArrayList<Book>();
library.add(new Fiction("The Saga of An Aga","F001",3,"A.Stove"));
library.add(new Fiction("Dangerous Cliffs","F002",4,"Eileen Dover"));
for (Book b: library) System.out.println(b);
System.out.println();
}
}
i get a return value of this:
book1.Fiction#15db9742
book1.Fiction#6d06d69c
book1.NonFiction#7852e922
book1.ReferenceBook#4e25154f
how can i convert the classes to return a string value instead of the object value? I need to do this without changing BookTest class. I know i need to use to string to convert the values. but i don't know how to catch the return value with it. could someone please point me in the right direction on how to convert this output into a string value?
You need to overwrite the toString() Method of your Book class. In this class you can generate a String however you like. Example:
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(this.author).append(": ").append(this.title);
return sb.toString();
}
You need to override the toString() method in your Book or Fiction class. The method is actually declared in the Object class, which all classes inherit from.
#Override
public String toString(){
return ""; // Replace this String with the variables or String literals that you want to return and print.
}
This method is called by System.out.println() and System.out.print() when they receive an object in the parameter (as opposed to a primitive, such as int and float).
To reference the variables in the method, you'll need to declare them in the class and store them via the class's constructor.
For example:
public abstract class Book {
private String name;
private String reference;
private int ownedCopies;
private int loanedCopies;
public Book (String name, String reference, int ownedCopies, int loanedCopies) {
this.name = name;
this.reference = reference;
this.ownedCopies = ownedCopies;
this.loanedCopies = loanedCopies;
}
#Override
public String toString(){
return name + ", Ref:" + reference + ", OwnedCopies: " + ownedCopies + ", LoanedCopies: " + loanedCopies; // Replace this String with the variables or String literals that you want to return and print.
}
}
The classes you have defined, don't store any values. It is in other words useful to construct a new book. You need to provide fields:
public abstract class Book {
private String name;
private String ref_num;
private int owned_copies;
private int loaned_copies;
public String Book (String name, String ref_num, int owned_copies, int loaned_copies) {
this.name = name;
this.ref_num = ref_num;
this.owned_copies = owned_copies;
this.loaned_copies = loaned_copies;
}
public String getName () {
return name;
}
//other getters
}
Now an object is basically a set of fields. If you want to print something, you can access and print one of these fields, for instance:
for (Book b: library) System.out.println(b.getName());
In Java, you can also provide a default way to print an object by overriding the toString method:
#Override
public String toString () {
return ref_num+" "+name;
}
in the Book class.
Need to give your object Book a ToString() override.
http://www.javapractices.com/topic/TopicAction.do?Id=55
Example:
#Override public String toString()
{
return name;
}
Where name, is a string in the Class.
I am hoping that you have assigned the passed arguments to certain attributes of the classes. Now, once you are done with that, you can override the toString() method in Book to return your customized string for printing.

Java: beginner help getting variable

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;
}

Pointing to a private method in Java?

I have a public method within a class that needs to point to a private method, how would I do this?
public class test1
{
private String lastName;
private String firstName;
public String name;
public void setup()
{
Scanner in = new Scanner(System.in);
System.out.println("Please enter the last name followed by the first name of" +
" a student: ");
lastName = in.next();
firstName = in.next();
}
private void setName() {
name = firstName + " " + lastName;
name = name.replaceAll(",([^,]*)$", "$1");
}
How would I point to the setName() method from the setup() method? And yes, I do need the setName() method even though I could just put all of that information into the setup() method.
One problem with your code is that your setName method is a setter method or "mutator method, and as such it should set the state of a property or field of your class. For it to work, you need to give it a parameter to allow anyone calling it to pass information in to the method, and yours does not do this.
Edit: I take that back. Your problem is your method is mis-named as it's not really a setter method at all. Change it to something else, say manipulateName(), and then call it after calling your public setter methods.
For example:
public Foo {
private String bar;
public void setup() {
//.... use Scanner to get bar String....
String innerBar = scanner.nextLine();
setBar(innerBar);
// here's the private method to manipulate stuff
changeBar();
}
public void setBar(String bar) {
this.bar = bar;
}
public String getBar() {
return bar;
}
private void changeBar() {
// do something with bar here
bar = bar.replaceAll(",([^,]*)$", "$1");
}

Categories

Resources