如何显示互相添加的字母的等效值?
我的输入是abc所以输出应该是6,因为:
a = 1
b = 2
c = 3
但我想显示互相添加的数字
离。
1 + 2 + 3 = 6
这是我的代码:
public static void main(String []args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter Alphabet");
String input = s.nextLine();
char[] charArray = input.toLowerCase().toCharArray();
int sum = 0;
for (char c : charArray) {
sum += (int)c-96;
}
System.out.println(sum);
}
答案 0 :(得分:0)
我建议您使用StringBuilder
来跟踪值,如下所示:
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter Alphabet");
String input = s.nextLine();
char[] charArray = input.toLowerCase().toCharArray();
int sum = 0;
StringBuilder builder = new StringBuilder();
int i = 1;
for (char c : charArray) {
sum += (int) c - 96;
builder.append((int) c - 96);
if(i != charArray.length)
builder.append(" + ");
else if(i == charArray.length)
builder.append(" = ");
i++;
}
builder.append(sum);
System.out.println(builder);
}