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. 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:
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 -
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.
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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.