这是我的代码:
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
String happyNumber = input.nextLine();
int happyNum = Integer.parseInt(happyNumber);
happyNum *= happyNum;
int answer = 0;
for (char ch : Integer.toString(happyNum).toCharArray()) {
int digit = ch - '0';
answer = digit * digit;
System.out.print(answer);
}
例如:
输入一个数字:7
输出是: 16 81
现在伙计们,我想增加16和81.总和将是97.我已经尝试过研究,但我仍然无法解决这个简单的问题。
答案 0 :(得分:1)
使用金额来跟踪总数=)
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
String happyNumber = input.nextLine();
int happyNum = Integer.parseInt(happyNumber);
happyNum *= happyNum;
int answer = 0;
int sum = 0; //NEW
for (char ch : Integer.toString(happyNum).toCharArray()) {
int digit = ch - '0';
answer = digit * digit;
sum = sum + answer;//NEW
System.out.print(answer);
}
System.out.print("Sum: " + sum);//NEW
尝试并理解代码的更改。我添加// NEW添加到我添加的每一行