java:将大写字符转换为整数
我正在处理一个USACO问题(ride),我正在尝试将大写字符(即“a”)转换为相应的int(对于“a”,它将是1),但它似乎不起作用。我目前正在做的是:java:将大写字符转换为整数,java,io,char,Java,Io,Char,我正在处理一个USACO问题(ride),我正在尝试将大写字符(即“a”)转换为相应的int(对于“a”,它将是1),但它似乎不起作用。我目前正在做的是: for(char c1 : st1ch) { int charint = (int)c1; totalcharsum1 = totalcharsum1*charint; } …以便将读取的字符串从文件(我将其转换为字符数组)转换为其int对应项。我假设(int)“A”等是1。然而,我的代码显然没有产生正确的结果。我相信这就是
for(char c1 : st1ch)
{
int charint = (int)c1;
totalcharsum1 = totalcharsum1*charint;
}
…以便将读取的字符串
从文件(我将其转换为字符数组)转换为其int
对应项。我假设(int)“A”等是1。然而,我的代码显然没有产生正确的结果。我相信这就是问题所在,因为我看不到其他问题。我没有找到解决这个问题的指南。当然,我的错误可能在其他地方,所以无论如何我都会在下面发布我的代码:
import java.io.*;
class ride {
public static void main(String[] arg) throws IOException{
BufferedReader reader = new BufferedReader(new FileReader ("ride.in"));
String st1 = reader.readLine();
String st2 = reader.readLine();
int totalcharsum1 = 1;
int totalcharsum2 = 1;
char[] st1ch = st1.toCharArray();
char[] st2ch = st2.toCharArray();
for(char c1 : st1ch)
{
int charint = (int)c1;
totalcharsum1 = totalcharsum1*charint;
}
for(char c2 : st2ch)
{
int charint = (int)c2;
totalcharsum2 = totalcharsum2*charint;
}
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("ride.out")));
if(totalcharsum1%47 == totalcharsum2%47)
{
out.println("GO");
}else{
out.println("STAY");
}
out.close();
System.exit(0);
}
}
我的问题是如何将大写字符转换为字母表上相应的整数?谢谢,山姆。减去他们的ASCII值
char ch = 'X';
int diff = ch -'A';
通过减去绝对ASCII值,可以将Java中的
char
转换为int
。下面是一个方法,它返回字符串中每个字符整数值的乘积(对于ride.java
)很有用:
publicstaticintmakenumber(字符串名){
int乘积=1;
//遍历字符串名称中的每个字符
对于(int i=0;i
“我假设并读到(int)“A”等将是1。”。。。我不知道你在哪里读到的,但是再也没有读过。大写字母-'A'+1
是字母表中大写罗马字母的(基于1的)索引'A'
实际上是Unicode中的代码点65,Java使用它来关联和计算数字。@BrianRoach我不会,是某个地方的博客(我想不起来)修复了这个问题。我会记住的。@SamuelBird没问题!如果这个答案有用,你介意接受吗?谢谢9分钟后,显然我可以。
public static int makeNumber(String name) {
int product = 1;
//iterate through each character in the String name
for (int i = 0; i < name.length(); i++) {
//get the character value
int charVal = (name.charAt(i) - 'A') + 1;
//multiply the product by the character value
product *= charVal;
}
return product;
}
}