public static String carRentalCode(String licensePlate) {
// precondition: licensePlate is a valid plate as described in pdf
// postcondition: return the car rental code for the licensePlate as described
int values = 0;
int ascii = 0;
int sum = 0;
int convert = 0;
int count = 0;
int a = 0;
char letter;
String license;
char[] ch = new char[licensePlate.length()];
for (int i = 0; i < licensePlate.length(); i++) {
ch[i] = licensePlate.charAt(i);
}
for(int i = 0; i< ch.length; i++)
{
if(Character.isDigit(ch[i]))
{
values += Character.getNumericValue(ch[i]);
}
if(Character.isAlphabetic(ch[i]))
{
ascii += (int) ch[i];
count++;
}
}
sum = values + ascii;
convert = sum%26 + 65;
letter = (char)convert;
String[] letters = licensePlate.split("\\d+");
String lowercase = Arrays.toString(letters).toLowerCase();
String code = Integer.toString(sum);
return letter + code + lowercase;
在这里,我应该根据给定的车牌(测试仪车牌为"123ABC456")返回租车代码。我剩下的唯一问题是我的小写字母返回,[[,abc]]而不是正确的答案[abc]。
您如何固定前面的空白区域,并且有两对而不是一对?还是有其他方法仅获取字符串中(ABC)与数字(123和456)分开的字母并返回它?
预期:```js L219[abc]
实际: ```js
L219[[, abc]]
我更改了一些代码,用于String.toCharArray()创建字符数组,而不是逐字符地将其复制,然后将所有数字替换为空字符串以仅获取字母字符
public static String carRentalCode(String licensePlate) {
// precondition: licensePlate is a valid plate as described in pdf
// postcondition: return the car rental code for the licensePlate as described
int values = 0;
int ascii = 0;
int sum = 0;
int convert = 0;
char letter;
char[] ch = licensePlate.toCharArray();
for (int i = 0; i < ch.length; i++) {
if (Character.isDigit(ch[i])) {
values += Character.getNumericValue(ch[i]);
}
if (Character.isAlphabetic(ch[i])) {
ascii += ch[i];
}
}
sum = values + ascii;
convert = sum % 26 + 65;
letter = (char) convert;
String lowercase = licensePlate.replaceAll("\\d+", "").trim().toLowerCase();
String code = Integer.toString(sum);
return letter + code + "[" + lowercase + "]";
}
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。