繁体   English   中英

Java toString()方法不适用于我的课程

[英]Java toString()-method doesn't work for my class

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

字符串方法。 这是某处的错误,这是由于尝试使用此方法将对象分发出去时,导致终端中出现一些疯狂的东西。

  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:这里我们构造了两个Object,使用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中强制转换了Objects。 我不知道哪里出了问题,但是错误必须在to.String()方法中的任何地方。

这个:

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

是你的问题。 你铸造和分配一个intchar ......这意味着你现在在你的任何字符集是与整数值的字符。 在您的情况下...没有具有该值的可打印字符,因此会出现“小方块”(在另一个终端中,您可能会看到问号)。

为了更好地说明,请尝试以下操作:

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

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

一种

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

不要那样做 删除这些行,并获得使用String串联时将自动发生的整数的文本表示形式:

String Beschreibung = x + "," + y;

还有其他方法可以做到这一点(例如String.valueOf()String.format() ),但这是最简单的。

(也不要大写变量名。Java中的变量应为camelCase并以小写开头。)

您无法像尝试的那样将数字转换为char,因为您将看到的只是数字的ASCII表示,这不是您想要的。 相反,为什么不让String通过使用String.format(...)为您完成繁重的工作:

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM