我创建了一个这样的类
public Move(char colour, int number) //a constructor takes 2 input
{
this.colour = colour;
this.number = number;
}
public static int convertColourtoNum(char colour)
{
int index = 0;
if (colour == 'R')
index = '0';
else if (colour == 'Y')
index = '1';
else if (colour == 'G')
index = '2';
else
index = '3';
return index; //return the colour in type int after being converted
}
然后在其他类中我使用这个方法来显示
Move m = new Move('R', 4);
System.out.println("Display " + m.convertColourtoNum(m.getColour()));
问题是代码应该显示
Display 0
但是,它显示
Display 48
为什么会发生这种情况?谢谢
最佳答案
问题出在我们的方法convertColourToNum
if (colour == 'R')
index = '0';
else if (colour == 'Y')
index = '1';
else if (colour == 'G')
index = '2';
else
index = '3';
注意您如何在数字周围使用 ''
。这使得 java 认为您有一个 char
,因此它实际上返回 0 的 ASCII 值并将其存储在 index
中。你应该做的是
if (colour == 'R')
index = 0;
else if (colour == 'Y')
index = 1;
else if (colour == 'G')
index = 2;
else
index = 3;
这样,java 就会意识到您需要 int
数据类型,并将在 index
中存储一个 int
。
关于java - 该方法未按方法中的预期显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49889328/