Java toString() - 方法对我的类不起作用

时间:2013-06-29 20:55:59

标签: java printing tostring

import java.io.*;

public class Bewertung {
  int schwarze;
  int weisse;

这个类构造了对象,它们必须属性为schwarze和weisse。默认构造器:

  public Bewertung() {
  schwarze = 0;
  weisse = 0;
  }

构造

  public Bewertung(int sw, int ws) {
  schwarze = sw;
  weisse = ws;
  }

To-String方法。这是某个地方的错误,因为当我试图通过使用这种方法给出一个对象时,我在终端中得到了一些疯狂的东西。

  public String toString() {
    int x = this.schwarze;
    int y = this.weisse;

    char x2 = (char) x;
    char y2 = (char) y;
    String Beschreibung = x2 + "," + y2;
    return Beschreibung; 
  }

此方法通过比较两个对象的属性来检查它们是否相同。

public boolean equals(Bewertung o) {  
 if (this.schwarze == o.schwarze && this.weisse == o.weisse) {
  return true;
}
else return false;
}

此方法使用您在终端中输入的属性创建一个新对象,工作正常。

public static Bewertung readBewertung() throws IOException {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
System.out.println("Gib die Zahl fuer Schwarz ein.");
String zeile;
    int wert=0;

    zeile=br.readLine();
    int eingabe1=(new Integer(zeile)).intValue();
System.out.println("Gib die Zahl fuer Weiss ein.");
zeile=br.readLine();
    int eingabe2=(new Integer(zeile)).intValue();

Bewertung neueBewertung = new Bewertung(eingabe1, eingabe2);
return neueBewertung;

}

Main-Method:这里我们构造两个对象,用readBewertung() - Method构造2个新对象,然后我们尝试打印它们并做一些其他的东西。一切 但印刷工作正常。

public static void main(String[] args) {
try 
{
Bewertung Bewertung1 = MeineBewertung1.readBewertung();
  System.out.println(Bewertung1.toString());
  Bewertung Bewertung2 = MeineBewertung2.readBewertung();
  System.out.println(Bewertung2.toString());
  if (Bewertung1.equals(Bewertung2)) {
  System.out.println("Die beiden Bewertungen sind identisch!");
  }
}
catch ( IOException e)
{
}


}

}

问题:我得到了一些正方形,而不是如何在String中投射的对象。我不知道出了什么问题,但错误必须在to.String() - 方法中的任何地方。

2 个答案:

答案 0 :(得分:4)

此:

char x2 = (char) x;
char y2 = (char) y;

你的问题。您正在投射并将int分配给char ...这意味着您现在拥有任何字符集与该整数值相关的字符。在您的情况下...没有具有该值的可打印字符,因此您获得“小方块”(在不同的终端中您可能会看到问号)。

为了更好地说明,试试这个:

int a = 65;
char c = (char)a;
System.out.println(c); 

如果你在第一个字节代码点中使用UTF-8或其他包含US-ASCII的字符集,你会看到:

  

A

因为65是ASCII中A的值(参见:http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters

不要那样做。删除这些行,并获得整数的文本表示,这些表示将在使用字符串连接时自动发生:

String Beschreibung = x + "," + y;

还有其他方法可以执行此操作(例如String.valueOf()String.format()),但这是最简单的方法。

(另外,不要大写变量名.Java中的变量应该是camelCase并从小写开始。)

答案 1 :(得分:2)

你不能像你正在尝试的那样从数字转换为字符,因为所有你会看到的数字的ASCII表示不是你想要的。相反,为什么不让String使用String.format(...)

为你做繁重的工作
public String toString() {
 int x = this.schwarze;
 int y = this.weisse;

 return String.format("%d, %d", x, y);
}

另外,请学习并使用正确的Java命名约定。方法和变量应以小写字母开头。