I use this site quite a lot, but I never wrote anything. Today I came across a problem whose solution I can’t find.
The problem is what I have int variablewith an unknown number of digits. I am invited to summarize all these numbers, and then print / shown_mechanical_value with all these numbers.
For example, the user enters the number "12345678", and at the end I need to get the message "Numbers 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 = 36". I know how to separate and sum all these numbers, but I don’t know how to save each number, and then show it, because not only do I not know the required number of digits, but I do not know their meanings either.
Usually it is not difficult to do, but for me this is the tricky part, because we have not studied such things as arrays, strings, indexes, etc., we are not allowed to use them. So, I have to do this with the simplest type of code.
So far I have the following:
import java.util.Scanner;
public class Numbers {
public static void main(String[] args) {
int number, result;
Scanner sc = new Scanner(System.in);
System.out.println("Enter number:");
number = sc.nextInt();
result = 0;
while (number > 0){
result = result + (number % 10);
number = number / 10;
}
System.out.println("This is where the message would go.");
}
}
source
share