Java。如何在循环中添加原始值 - (for)

Java. How to add primitive values in a loop - (for)

我正在尝试取一个随机数并将其拆分,然后将其数字相加,因此数字“3457”将是....... 3 + 4 + 5 + 7。但是我'我遇到了必须在循环中添加值的问题,但我发现这很困难,因为我循环中的大多数类型都是原始类型,因此我不能真正使用 "nextInt()" 方法......所以我的问题...如何在循环中添加值。 到目前为止,这是我的代码...

import java.util.Scanner;
public class HellloWorld {

    public static void main(String[] args) {
       Scanner input = new Scanner(System.in);
           try {
           System.out.println("Please Enter your number: " + "\n");
           int int1 = Integer.parseInt(input.next());
           int life = String.valueOf(int1).length();
           for (int i = life; i >= 1; i--) {
           int int2 = int1 / (int)(Math.pow(10, i-1));
           int int3 = int2 % (int)(Math.pow(10,1));

               if (i == 1) {
            System.out.print(int3 + " = ");
        } else {
            System.out.print(int3 + " + ");
        }
    }

    } finally {
        input.close();
    }
}
}
  1. 对于求和的情况 - 您可以使用另一个变量,假设 sum 有点像 -

    int sum = 0;
    
    for(...) {
    ....
    sum = sum + yourDigit;
    if{...} else {...}
    } //end of for loop
    System.out.println(sum);
    
  2. 你的逻辑似乎不是在求和 - 尝试使用 (1) 看看你是否得到了你想要的。

  3. 想到

    int sum = 0; 
    int input = int1; 
    while (input != 0) {
       int lastdigit = input % 10;  //(right to left) one's to tens to hundreds place value
       sum += lastdigit; // sum = sum + lastDigit
       input /= 10; // your if..else can be based on this value
    }
    

您可以像这样使用 Stream 执行此操作:

public static void main(String... args) {
  Scanner sc = new Scanner(System.in);
  String strNum = sc.next();
  int sum = Arrays.stream(strNum.split(""))
              .mapToInt(str -> Integer.parseInt(str))
              .sum();
  System.out.println(sum);
}

我奇怪但史诗般的做法:

public static void main(String[] args) {
    int a = 1234;   //say you get that number somehow... lets say thru Scanner  
    String b = String.valueOf(a);   //convert to a string   
    int result = 0;     
    for (int i = 0; i < b.length(); i++) {
        result = result + Integer.parseInt(Character.toString(b.charAt(i))); // here a conversation is happening of epic scale
    }
            System.out.println("result is: "+ result);
}