java - 该方法未按方法中的预期显示

标签 java class

我创建了一个这样的类

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/

相关文章:

python - Python 类中的数学方法

java - Hibernate Lazy 集合的正确初始化

java - JSESSIONID 是如何传递的?作为 header 参数还是作为 cookie 参数?

javascript - javascript中的静态方法可以调用非静态方法吗

class - Matplotlib 窗口类? OO 相当于 matplotlib.pyplot.close()?

c++ - 类声明后编译错误,Main 没有 "see"类

python - 为什么我的类(class)会引发 AttributeError?

java - 如何在一段时间内禁用 JButton?

java - Docker 运行小型 Java 类 : Could Not Find Or Load Main Class (Even Though It Exists)

java - 进程和退出代码