gpt4 book ai didi

java - 为什么int类型方法允许字符类型作为返回值?

转载 作者:行者123 更新时间:2023-12-01 18:23:27 26 4
gpt4 key购买 nike

这是我的代码,但我不明白如何 int getValue()方法接受 char类型作为返回值。运作如何?有人可以解释一下这个方法是如何工作的吗?

public class CharToInteger {
private static Scanner input;
public static int getValue(char character){
return character;
}

public static void main(String[] args) {
input = new Scanner(System.in);
System.out.println("Enter a character to get value of it:");
String inputString=(String) input.next();
char inputCharacter=inputString.charAt(0);
System.out.println(getValue(inputCharacter));
}

}

提前致谢:)

最佳答案

public static int getValue(char character){
return character;//<-- unicode value is being returned, e.g. char 0 -> int 48
// char ranges from 0 - 65535
}

来自 JSL:

5.1.4. Widening and Narrowing Primitive Conversion

The following conversion combines both widening and narrowing primitive conversions:

byte to char

First, the byte is converted to an int via widening primitive conversion (§5.1.2), and then the resulting int is converted to a char by narrowing primitive conversion (§5.1.3).

see more :

关于java - 为什么int类型方法允许字符类型作为返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26989135/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com