[英]Java. How to add primitive values in a loop - (for)
I'm trying to take a random number and split it, then add its digits, so the number "3457" will be........ 3 + 4 + 5 + 7. But I've come across the problem of having to add the values in the loop but i find it difficult since most of my types within my loop are primitive types thus i cant really use the "nextInt()" method... So down to my question... how do you add values within a loop. 我正在尝试获取一个随机数并将其分割,然后添加其数字,因此数字“ 3457”将是........ 3 + 4 + 5 +7。但是我遇到了问题必须在循环中添加值的方法,但是我发现这很困难,因为我循环中的大多数类型都是原始类型,因此我无法真正使用“ nextInt()”方法...所以我的问题...该怎么办您可以在循环中添加值。 Here's my code so far...
到目前为止,这是我的代码...
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();
}
}
}
You can do this using Stream
like this: 您可以使用
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);
}
For the sum case - You can use another variable, lets say sum
somewhat as - 对于sum的情况-您可以使用另一个变量,让
sum
有点像-
int sum = 0; for(...) { .... sum = sum + yourDigit; if{...} else {...} } //end of for loop System.out.println(sum);
Your logic seems not to be doing the sum - try using (1) to see if you get what is desired. 您的逻辑似乎没有做总和-尝试使用(1)来查看您是否得到了期望的结果。
Think of 考虑到
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 }
My weird but epic way of doing it: 我的怪异但史诗般的方式:
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.