这是我的代码:

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。

最佳答案

用总和来跟踪总数=)

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

09-25 22:17