java - 如何在java中将char映射到int
问题描述
我对编程很陌生,无法解决以下问题。
我有一个 char 类型的坐标列表,我需要将其转换为数字(int 类型)。因此,例如 char a 应该是 int 0、char b - int 1 等。所以我使用 switch 语句构建了以下代码。我想将它作为方法调用,但我不断收到以下错误:此方法必须返回 int 类型的结果。有人可以解释我做错了什么吗?我也尝试过使用 return 而不是 int .. = 0; 但这也无济于事。
int x () {
char ch = 'c';
switch (ch)
{
case 'a':
int a = 0;
break;
case 'b':
int b = 1;
break;
case 'c':
int c = 2;
System.out.println(c);
break;
case 'd':
int d = 3;
break;
case 'e':
int e = 4;
break;
case 'f':
int f = 5;
break;
case 'g':
int g = 6;
break;
case 'h':
int h = 7;
break;
}
}
解决方案
If your chars are just the same you mentioned you can use something like this.
static int toNumber(char chr) {
return (chr - 97);
}
The concept is this: a char is encoded as a byte, which is a number. Check out a related ASCII table where you can see that 'a' has the value 97 (decimal), 'b' has 98... So if we subtract 97 from all our chars we can reach the desired values.
char byte(decimal) char value -97 a 97 0 b 98 1 ... ... ... z 122 24
But the problem with your function is the fact that the return statement was missing. You can make it work by changing it to this
int x() {
char ch = 'c';
int value = 0;
switch (ch) {
case 'a':
value = 0;
break;
case 'b':
value = 1;
break;
case 'c':
value = 2;
System.out.println(c);
break;
case 'd':
value = 3;
break;
case 'e':
value = 4;
break;
case 'f':
value = 5;
break;
case 'g':
value = 6;
break;
case 'h':
value = 7;
break;
}
return value;
}
推荐阅读
- wordpress-shortcode - Wordpress 中以逗号分隔的类别列表
- nativescript - Nativescript Vue - 键入时文本字段更改焦点在另一个字段上
- webpack - 摇树不适用于 Babel polyfill + lodash + webpack
- flutter - 必须向 Text 小部件提供非空字符串。断言失败:第 378 行 pos 10:'data != null'
- c# - 在 C# 中正确的 ID 验证
- geojson - 使用 react-leaflet 从 GeoJSON 显示不同类型对象的最有效方法
- linux - Ubuntu - 从脚本文件切换到 root 用户而不提示输入密码
- safari - VO Button + Space 在带有 select2 的 Safari 上不起作用
- postgresql - 无法显示超表信息:timescaledb_information.hypertable 不存在
- r - 使用 ggplot2 绘制使用 NLS 获得的非线性回归