Java getClass().getName() it returns the class not the name - java

The output was Card Card. It was suppose to be unknown Jane. How do i fix this? I tried to fix it with Card.getClass().getName() but that gives me another error non-static method getClass() cannot be referenced from a static context.
public class Card
{
private String name;
public Card()
{
name = "unknown";
}
public Card(String name1)
{
name = name1 ;
}
public String getName()
{
return name;
}
public String toString()
{
return getClass().getName();
}
}
public class CardTester
{
public static void main(String[] args)
{
Card card ;
card = new Card() ;
System.out.println(card) ;
System.out.println("unknown WAS EXPECTED") ;
card = new Card("Jane") ;
System.out.println(card) ;
System.out.println("Jane WAS EXPECTED") ;
}
}

Your toString() method prints the name of the class of the object:
return getClass().getName();
The object is an instance of Card, so its class is Card.class, whose name is Card. You want to print the value of the name field. So you simply need
return name;

getClass() returns the Class object representing the "Card" class; therefore the code does not refer to Card#getName method, but rather to Class#getName which dutifully returns "Card".
Simply remove getClass():
public String toString()
{
return getName();
}
The previous error (wrt "static") was using Card.getName() - don't prefix a type to invoke an instance method.

Related

Adding elements to ArrayList<Type> and print them in java [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 1 year ago.
I'm trying to create a class called "NewType" where there is a string as attribute. In another class in the same package I created an ArrayList<NewType>.
How can I print the string parameters that I pass every time I create a NewType object (new NewType("Hello"))? Because using a for and printing just the object, it prints only the address of the new objects created. I know that I could just create an ArrayList<String>, but I need this also to understand how to work with the class types.
Here is what I tried:
Token j=new Token(part); //Token is th e "NewType" class type
tokenfinal.add(j); //tokenfinal is the ArrayList<Token>
//CLASS TOKEN
public class Token {
public String tok;
public Token(String tok) {
this.tok=tok;
Let's see the following example:
public class Main {
static class Person {
private String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
#Override
public String toString() {
return String.format("Person name: %s", this.getName());
}
}
public static void main(String[] args) {
List<Person> personList = new ArrayList<>();
personList.add(new Person("Test_Name"));
personList.add(new Person("Name_Name"));
personList.forEach(System.out::println);
}
}
Result:
Person name: Test_Name
Person name: Name_Name
You need to override toString() method in your Token class and customize it to return your field String tok or any other field you create
I am not sure if I understood your question, but you can do print value of the input string via override the toString method int the NewType class.
public class NewType {
private String text;
public NewType(String str) {
text = str;
}
#Override
public String toString() {
return text;
}
}
By this, printing the class instance in print or println will call the overrided toString method.

Getter and assertsEquals function

I have written a code for Person class and in that class create a constructor Person and argument name. Now I have to create an instance of this class will offer a getter for the person's name and also create an instance of this class will respond to a greet method that accepts one argument: message.
When the message is "Hello", greet must return:
Hi, I'm {{name}}
When the message is "Goodbye", greet must return:
Bye
When the message is anything else, greet will return the message that it was provided. I have a tested case code but I am stuck with assertEquals() function and getter function. Now I am facing error with assertfunction. Can anybody please tell me how does assertfucntion and getter works? I have implemented getter in my code, I'm but not sure whether I did it right.
Here's my code:
class Person
{
private String name;
Person(String n)
{
n = name;
}
String GetName()
{
return this.name;
}
public void greet(String t)
{
if (t == "Hello")
{
System.out.println("Hi my name is "+name);
}
else if (t == "Goodbye")
{
System.out.println("bye");
}
else
System.out.println("Hi, my name is"+name);
}
}
Test code:
import static org.junit.Assert.*;
import org.junit.Test;
import org.junit.Before;
public class TestPerson {
private Person jeff;
private Person susy;
#Before
public void setup() {
jeff = new Person("Jeff");
susy = new Person("Susy");
}
#Test
public void testGetName() {
assertEquals("Jeff", jeff.GetName());
}
#Test
public void testGreetHelloJeff() {
assertEquals("Hi, I'm Jeff", jeff.greet("Hello"));
}
#Test
public void testGreetHelloSusy() {
assertEquals("Hi, I'm Susy", susy.greet("Hello"));
}
#Test
public void testGreetGoodbye() {
assertEquals("Bye", jeff.greet("Goodbye"));
}
#Test
public void testGreetOther() {
assertEquals("Yo", jeff.greet("Yo"));
}
}
You cannot compare a String and the return value of a method that returns void.
Your Person class is odd. You have it too closely tied to System.out, which is not useful.
Your code has a lot of problems for such a small sample size. Here's what I might suggest:
public class Person {
private String name;
Person(String n) {
this.name = n;
}
String getName() {
return this.name;
}
public String greet(String t) {
if ("Hello".equals(t)) {
return String.format("Hi my name is %s", name);
} else if ("Goodbye".equals(t)) {
return "bye";
} else {
return String.format("Hi, my name is %s", name);
}
}
}
See your method returns void:
public void greet(String t)
How do you expect to get and assert a values of void?
Change void to String and do return a message string.
Also do not use == rather .equals(..)
"Hello" case seems does the same as default. Better do:
public class Person {
private String name;
Person(String name) {
this.name = name;
}
String getName() {
return this.name;
}
public String greet(String m) {
if ("Goodbye".equals(m)) {
return "bye";
} else {
return String.format("Hi, my name is %s", name);
}
}
}
By calling assertEquals("Bye", jeff.greet("Goodbye")); you're comparing the String "Bye" to void since .greet returns void.
Change greet to this:
public String greet(String t){
if(t.equals("Hello"))
return "Hi my name is " + name;
else if(t.equals("Goodbye"))
return "bye";
else
return "Hi, my name is" + name;
}
And then you can use the assertEquals(String, String) like:
assertEquals("bye", jeff.greet("Goodbye"));
In Java when comparing Strings use .equals() instead of ==. So 'if(t=="Hello")"' would be 'if(t.equals("Hello"))'
Method names should start with a lower case letter.
Also String comparison is case sensitive so make sure you are using the correct case when comparing your Strings.
It doesn't make sense to test the greet(String) method using assertEquals, since the method doesn't return anything. The assertEquals is used to assert whether the actual result returned from a tested method is equal to an expected value that you provide, just like the testGetName above.
It seems more appropriate to change void greet(String) to String greet(String) which returns a greeting message according to the t argument to make your code more testable.
Moreover, you should use aStr.equals(bStr) instead of aStr == bStr to compare two String. == just compare the reference of the two String object rather than their values.

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.

String s1=new String("demo"); While printing why does it give output as the given string?

If we create a String like below and print the value:
String s=new String("demo");
System.out.println(s);
...the output is:
demo
Good. This is the expected output. But here String is a class. Remember that. Below is another example. For example, take a class like this:
class A
{
public static void main (String args[])
{
A a =new A();
A a1=new A("hi"); //we should create a Constructor like A(String name)
System.out.println(a1); //here O/P is address
}
}
My doubt is that I created the A instance in the same way I created the new String object, and I printed that object. So why does it not print the given String for the instance of A?
You need to override the Object#toString() in your class. By default, the toString() method of Object is called.
Also, to print the value, you just need to override the method as internally a call will be made to the toString() method when this statement is executed.
System.out.println(a1);
Sample overriden toString() method.
#Override
public String toString() {
// return a string value
return "The String representation of your class, as per your needs";
}
You have to override toString() method in your class the way you want to print something when call System.out.println();. In String class toString() method has override and you will get out put above due to that.
As pointed out already, you need to override the default toString() method inherited from the Object class. Every class automatically extends the Object class, which has a rather simple toString(), which can't know how to turn your particular object into a String. Why should it, especially if your class is arbitrarily complex? How is it supposed to know how to turn all your class's fields into a "sensible" string representation?
In the toString() of your class, you need to return the string that you want to represent your class with. Here is a simple example:
class A {
String foo;
public A(String foo) {
this.foo = foo;
}
public String toString() {
return foo;
}
}
public class sample {
public static void main(String[] args) {
A a = new A("Hello world!");
System.out.println(a);
}
}
String is a class whose purpose is to hold a string value and will return that value if referenced. When you use other classes, you will usually want to add other behavior. If you want to use the class to hold different values that you can set (on object creation or later in processing) you may want to use "setter" and "getter" methods for such values.
Here is an example:
public class Snippet {
private static final String C_DEFAULT_VALUE = "<default value>";
private String name;
private static Snippet mySnippet;
public Snippet() {
}
public Snippet(String value) {
setName(value);
}
/**
* #param args
*/
public static void main(String[] args) {
if (args != null && args.length > 0) {
mySnippet = new Snippet(args[0]);
} else {
mySnippet = new Snippet(C_DEFAULT_VALUE);
}
System.out.println(mySnippet.getName());
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

A parameters' variable as parameter

I have an Object Human:
public class Human {
String name;
public Human(String name){
this.name = name;
}
}
In my main Class I have an instance of this human "John".
With a function called getVarOfObject() I want to get John's name:
public class Example {
public static Object getVarOfObject(Object obj, Object var){
return obj.var;
}
public static void main(String[] args) {
Human john = new Human("John");
String johnsName = getVarOfObject(john, name);
}
}
I know you could just type john.name but in my case I need to have a function which can do this.
You can use this code
Field field = <Your object>.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
return (String) field.get(object);
You can't do this except reflectively.
Please note that this wizardry can lead to errors, subtle issues, exceptions, performance losses, asphyxiation, drowning, death, paralysis, or fire.
Object obj is the object, and String field is the name of the field.
Class clazz=Human.getClass(); //or for class-independence use `obj.getClass()`.
Field fd=clazz.getField(name);
fd.get(obj);
Why don't you use accessor methods (getters and setters)?
In Human:
public String getName() {
return name;
}
and in your main method:
Human john = new Human("John");
String johnsName = john.getName();

Categories

Resources