Problems with ToString and Output

I need help with my program.

This is my purpose

I already wrote the code, but when I go to print my code, it only outputs Int. (Note that my formatting is much better - I have not used this site).

This is my class file:

public class Card
{

  //instance variables
  public String rank;
  public String suit ;
  public int cardValue;

  //constructor

 public Card(String rank, String suit, int cardValue)
 {
  this.rank = rank;  
  this.suit = suit;
  this.cardValue = cardValue; 
 }

 //accessors
 //get methods

 public String getrank()   
 {     
 return rank;   
 }

 public String getsuit()
 {
 return suit; 
 }

 public int getcardValue() 
 {
 return cardValue;  
 }

 //toString
 public String toString()
  {
    String output = 
    "The" + rank + "of" + suit + "=" + cardValue + "\n";
    return output;
  }
}

This is my runner file:

import static java.lang.System.*;

public class CardRunner
{
 public static void main( String args[] )
 {

 Card bob = new Card("ACE", "SPADES", 11); 
 System.out.println(bob.cardValue); 
 }
}
+4
source share
5 answers

When you call System.out.println(bob.cardValue);, you only print cardValueyour property Card.

You must print an instance Cardto execute your method toString:

System.out.println(bob); 
+3
source

If you want to output all the data from bob, you should do this:

System.out.println(bob.toString());
+1
source

 System.out.println(bob); 
0

System.out.println(bob.cardValue);, . , .

: - "System.out.println(bob);" toString().

 //toString
 public String toString()
  {
    String output = 
    "The" + rank + "of" + suit + "=" + cardValue + "\n";
    return output;
  }
0

, System.out.println(bob.cardValue); .

overriden toString() " (, , , java Object)

toString() - (bob.cardValue) - , (), (bob) (bob - , "":)).

toString(), :

System.out.println(bob);  //in fact, will be called toString() also
System.out.println(bob.toString());

//or if you just need save instance in your custom string format in some *String* variable
String bobInMyString = bob.toString();
String bobInMyStringUsingCasttoString = (String) bob; //should also call toString()

Btw it should look like (annotation for the compiler):

@Override
 public String toString()
  {
    String output = 
    "The" + rank + "of" + suit + "=" + cardValue + "\n";
    return output;
  }
}

If you ask why to use toString () override , see for example. for this very good example (complex numbers), it is useful for custom classes or for writing an object to a file, etc.

0
source

Source: https://habr.com/ru/post/1606680/


All Articles