What I need to do is make a number generator that stops when it generates 10 and shows how many attempts there was until 10 was reached. I also have to use only while loops for this. Here's my code now:
public static int RandomOccurrence()
{
int randNumber = (int)(Math.random()*20 + 1);
int count = 0;
while(randNumber != 11){
System.out.println("The number generated is " + randNumber);
count = count + 1;
}
return count;
}
and here's the function call:
int number = RandomOccurrence();
System.out.println("It took " +number +" tries before 10 was generated");
System.out.println();
System.out.println();
But when I run the code it prints "the number generated is 2" infinitely.
Here's a fixed version of your code, which mostly involves moving the line that gets a random number into the while loop:
public static int RandomOccurrence()
{
int randNumber = 0;
int count = 0;
while(randNumber != 10){//I changed the 11 to 10 because you said you wanted to stop at 10
randNumber = (int)(Math.random()*20 + 1);//added
System.out.println("The number generated is " + randNumber);
count = count + 1;
}
return count;
}
System.out.println(RandomOccurrence());
Sample result:
The number generated is 1
The number generated is 4
The number generated is 20
The number generated is 19
The number generated is 10
5
I really prefer to point the user towards the answers for homework problems instead of giving them code that works. Because we're trying to "teach a man to fish."
The problem with the original code is that it must generate another random number within the while loop. The simplest way to do this is to copy-and-paste the same function-call that you used to generate the first one.
P.S.: You'll very quickly now see that "there's more than one way to do it!"
you should update your random number every time the while loop gets executed:
So randNumber = (int)(Math.random()*20 + 1); should be inside the loop
public static int RandomOccurrence(){
int count = 0;
int randNumber = 0;
while(randNumber != 11){
randNumber = (int)(Math.random()*20 + 1);
System.out.println("The number generated is " + randNumber);
count = count + 1;
}
return count;
}
public static void main(String...args){
int number = RandomOccurrence();
System.out.println("It took " +number +" tries before 10 was generated");
System.out.println();
System.out.println();
}
I hope I could help
Here's a 1-liner:
long count = IntStream.generate(() -> (int)(Math.random() * 20 + 1))
.takeWhile(i -> i != 11).count();
See live demo.
Related
I'm a Java beginner, please bear with me. :) I haven't learned anything like if statements and such yet, I've only learned about loops, variables, and classes. I need to write a single loop which produces the following output:
10 0 9 1 8 2 7 3 6 4 5 5
I can see from the segment, that the difference between the numbers is reduced by one, so from 10 to 0 it is subtracted 10, then from 0 to 9 it is added by 9, and it goes on alternating between adding and subtracting.
My idea was to create the loop where my variable i = 10 decreases by 1 in the loop (i--) but I'm not quite sure how to alternate between adding and subtracting in the loop?
public class Exercise7 {
public static void main(String[] args) {
for(int i = 10; i >= 0; i--) {
System.out.print(i + " ");
}
}
}
Why not have two extra variables and the increment one and decremented the other:
int y = 0;
int z = 10;
for(int i = 10; i >= 5; i--) {
System.out.print(z + " " + y + " ");
y++;
z--;
}
Output:
10 0 9 1 8 2 7 3 6 4 5 5
However we can also do this without extra variables:
for(int i = 10; i >= 5; i--) {
System.out.print(i + " " + 10-i + " ");
}
I don't think the OP actually wanted somebody to do their homework for them, so I'm gonna stick to answering the question they actually asked: how to alternate between two operations within a loop (so they can keep the algorithm they came up with :)).
There's a nifty "trick" that's very often used when we want to do something every other iteration in most programming languages. You'll most definitely come across it in your life, and it could be perplexing if you've got no clue what's going on, so here it goes!
The modulo (%) operator will yield the remainder of the division between its operands.
For instance, consider the following: 7 ÷ 2 = 3.5
When working for integers, you'd say that 7 ÷ 2 = 3, then you're left with 1.
In this case, when all variables are ints, in Java, 7 / 2 would be 3 and 7 % 2 is 1.
That's modulo for you!
What's interesting about this operator is inherent to what's interesting about division in general, and one case in particular: the remainder of a division by 2 is always either 0 or 1... and it alternates! That's the key word here.
Here comes the "trick" (not really a trick, it's basically a pattern considering how widely used it is) to alternating operations over iterations:
take any variable that is incremented every iteration in a loop
test for the remainder of the division of that variable by 2
if it's 0, do something, otherwise (it'll be 1), take the alternate path!
In your case, to answer your actual question (although others do have good points, I"m not trying to take that away from anybody), you could consider using something like that:
if( i % 2 == 0 ) {
// i is even, subtract
} else {
// i is odd, add
}
That'd allow you to keep going with the algorithm you initially thought of!
public class exercise7 {
public static void main(String[] args) {
for(int i = 10; i >= 5; i--) {
System.out.print(i + " " + (10-i) + " ");
}
}
}
Or you can do it this way, if you want to be a wiseass ;)
for(int i = 0, arr[] = {10,0,9,1,8,2,7,3,6,4,5,5}; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
This looks a bit like a homework assignment, so I won't give you working code.
But remember that you can put multiple print statements inside the for loop. You don't necessarily have to iterate 10 times to get your output. 5 times is totally enough. And as already stated in a comment above: the numbers alternate between i and 10-i, for the right range of i.
replace i >= 0 with i >= 5
add this : System.out.print((10-i--) + " ");
starting from what you did
public class Exercise7 {
public static void main(String[] args) {
for(int i = 10; i >= 5; ) {
System.out.print(i + " " + (10-i--) + " ");
}
}
}
Somethings don't need overthinking:
public class Answer2 {
public static void main(String[] args) {
for (int i = 0; i <= 5; i++){
System.out.println(i);
System.out.println(10 - i);
}
}
}
edit
You CAN and should generalize your task. Here is an example how you could do it (I won't write the method, since it's your job - instead I'll alter my answer just to show you the possibilities)
public class Answer2 {
private static final Random RANDOM = new Random();
public static void main(String[] args) {
//You can use any upper bound for 'someLength'
int someLength = 1 + RANDOM.nextInt(20);
for (int i = 0; i <= someLength / 2; i++) {
System.out.println(someLength - i);
System.out.println(i);
}
}
}
Who said that you can only use one System.out.print in the loop?
for (int i=0; i < 5; i++) {
System.out.print((10 - i) + " " + (i + 1) + " ");
}
You should think about generalizing the series. As you have observed, the series alternates between addition and subtraction. Also, the difference goes down by one at each step. You can define variables for these two and adjust them in the loop.
public static void main(String[] args) {
int term = 10;
int sign = 1;
for(int delta = 10; delta >= -1; delta--) {
System.out.print(term + " ");
sign = -1 * sign;
term = term + sign * delta;
}
}
Simply run a loop either starting from 0 or starting from 10.
1.
If you start from 10
for(int i=10;i>=5;i--){
System.out.print(i + " " + (10-i) + " ");
}
2.
If you start from 0
for(int i=0;i<=5;i++){
System.out.print((10-i) + " " + i + " ");
}
The output will be:
10 0 9 1 8 2 7 3 6 4 5 5
I tried this code. It worked for me.
for(int i = 10; i >= 5; i--) {
System.out.print(i + " ");
System.out.print(10-i + " ");
}
This is here. The output list is a list of combinations to make 10;
10 0 9 1 8 2 7 3 6 4 5 5
10 + 0 = 10
9 + 1 = 10
8 + 2 = 10
7 + 3 = 10
6 + 4 = 10
5 + 5 = 10
int n = 10;
int half = n / 2;
if(n % 2 == 1){
half++;
}
for(int x = n; x >= half;x--){
int remainder = n % x;
if(remainder == 0){
remainder = n - x;
}
System.out.print(x);
System.out.print(" ");
System.out.println(remainder);
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
Anyone knows how to run this program using 4 variables only? I tried using 1 variable for min and max "lowhigh" but I was having a hard time figuring out where to put the statements.
int numbers[] = new int[5];
int low = 0; int high = 0;
for(int count = 0; count < numbers.length; count++){
System.out.print("Please enter a number: ");
int number=s.nextInt();
if (count == 0) {
low = number;
high=number;
} else {
if(number < high) {
high= number;
}
if(number > low){
low = number;
}
}
numbers[count] = number;
}
double ave = numbers[0]+numbers[1]+numbers[2]+numbers[3]+numbers[4]/5;
System.out.println("Highest: " +high);
System.out.println("Lowest: " +low);
System.out.println("The average of all number is: " +ave); }}
Another way to do it in Java 8.
int numbers[] = new int[5];
for(int count = 0; count < numbers.length; count++){
System.out.print("Please enter a number: ");
int number=s.nextInt();
numbers[count] = number;
}
LongSummaryStatistics statistics = Arrays.stream(numbers)
.asLongStream()
.summaryStatistics();
System.out.println("Highest: " + statistics.getMax());
System.out.println("Lowest: " + statistics.getMin());
System.out.println("The average of all number is: " + statistics.getAverage());
Looks like your logic is backwards to finding high and low. Also your average wont work because order of operations. Need parens
int numbers[] = new int[5];
int low = Integer.MAX_VALUE; int high = Integer.MIN_VALUE;
for(int count = 0; count < numbers.length; count++){
System.out.print("Please enter a number: ");
int number=s.nextInt();
if (count == 0) {
low = number;
high=number;
} else {
if(number > high) {
high= number;
}
if(number < low){
low = number;
}
}
numbers[count] = number;
}
double ave = (numbers[0]+numbers[1]+numbers[2]+numbers[3]+numbers[4])/5;
System.out.println("Highest: " +high);
System.out.println("Lowest: " +low);
System.out.println("The average of all number is: " +ave); }}
You don't have to use an array if all you're doing is finding the min, max and mean.
final int COUNT = 5; //this is just to be neat, and not needed as a variable.
int low = Integer.MAX_VALUE;
int high = Integer.MIN_VALUE;
int sum = 0;
for(int i = 0; i < COUNT; i++){
int n = s.nextInt();//or whatever
if(n > high)
high = n;
if(n < low)
low = n;
sum += n;
}
System.out.println("Max: " + high);
System.out.println("Min: " + low);
System.out.println("Average: " + ((double) sum) / COUNT);
Based on what you mean by 4 variables, this may or may not work. final int COUNT is not really required and 5 can be put in directly instead.
This answer likely goes well beyond the scope of the question, but since the requirements/restrictions are not listed in full, it may still be a valid answer.
With a super strict interpretation of "4 variables", even the Scanner variable s counts.
Using streams, it can be done with 3 variables:
Scanner s; // variable 1
List<Double> values; // variable 2
String line; // variable 3
s = new Scanner(System.in);
values = new ArrayList<>();
while (true) {
System.out.print("Please enter a numbers, or press enter when done: ");
if ((line = s.nextLine().trim()).isEmpty())
break;
values.add(Double.valueOf(line));
}
if (values.isEmpty())
return;
System.out.println("Minimum: " + Stream.of(values.toArray(new Double[values.size()]))
.mapToDouble(Double::valueOf)
.min().getAsDouble());
System.out.println("Maximum: " + Stream.of(values.toArray(new Double[values.size()]))
.mapToDouble(Double::valueOf)
.max().getAsDouble());
System.out.println("Average: " + Stream.of(values.toArray(new Double[values.size()]))
.mapToDouble(Double::valueOf)
.sum() / values.size());
Sample output
Please enter a numbers, or press enter when done: 10
Please enter a numbers, or press enter when done: 42
Please enter a numbers, or press enter when done: 19
Please enter a numbers, or press enter when done: 88
Please enter a numbers, or press enter when done: 1
Please enter a numbers, or press enter when done: 3774
Please enter a numbers, or press enter when done:
Minimum: 1.0
Maximum: 3774.0
Average: 655.6666666666666
There is no point in the numbers[] array; so eliminate that.
You need a control variable for the loop, a temporary storage for the input, then three running variables for min, max and sum (average is sum devided by count, which seems to be fixed to 5).
Thats 5 variables, and you strictly need all of them. Its possible to stuff multiple values into a single variable, but I highly doubt thats what you're supposed to do.
Depending on what the requirements really are (I presume this is homework), one of the five I named above doesn't count as a variable per requirement (most likely the loop control or the temporary input storage).
Edit: Here's a variant using multiple values encoded in one variable that works with three variables (or four if you count the scanner, which I replaced with random for my convinience):
public class HighLowAverage {
public static void main(String[] args) {
long sum = 0;
long highLow = 0x8000_0000_7FFF_FFFFL;
long countNumber = 0;
for (; (countNumber >> 32) < 5; countNumber += 0x1_0000_0000L) {
countNumber = (countNumber & 0xFFFF_FFFF_0000_0000L)
| ((int) (Math.random() * 100) & 0xFFFF_FFFFL);
System.out.println(((countNumber >> 32) + 1) + ". number is: " + (int) countNumber);
sum += (int) countNumber;
if ((highLow >> 32) < (int) countNumber)
highLow = (highLow & 0xFFFF_FFFFL) | (countNumber << 32);
if (((int) highLow) > (int) countNumber)
highLow = (highLow & 0xFFFF_FFFF_0000_0000L) | (countNumber & 0xFFFF_FFFFL);
}
System.out.println("Average: " + ((double) sum) / (countNumber >> 32));
System.out.println("Min: " + (int) highLow);
System.out.println("Max: " + (highLow >> 32));
}
}
The techniques used are bit-shifting and masking to use the upper/lower half of the long datatype as independendly accessible values. Note amount of complicated expressions necessary as well as the numerous constansts in the expressions plus typecasts almost everywhere.
This is code you should never ever use - it works, but even an experienced programmer will need an excessive amount of thinking to figure out if its working correctly. My guess is that a typical beginner class teacher will have trouble understanding it at all.
Edit2: Scratch the above, it can be done with one variable. How? By replacing multiple variables with an array:
public static void main(String[] args) {
long[] vars = new long[5];
vars[1] = Long.MIN_VALUE;
vars[2] = Long.MAX_VALUE;
for (vars[0] = 0; vars[0] < 5; ++vars[0]) {
vars[4] = (int) (Math.random() * 100);
System.out.println((vars[0] + 1) + ". number is: " + vars[4]);
vars[3] += vars[4];
if (vars[4] > vars[1])
vars[1] = vars[4];
if (vars[4] < vars[2])
vars[2] = vars[4];
}
System.out.println("Average: " + ((double) vars[3]) / vars[0]);
System.out.println("Min: " + vars[1]);
System.out.println("Max: " + vars[2]);
}
Needless to say thats still confusing code. Each index of the vars array is used to hold one of the variables (0 = loop control, 1 = min, 2 = max, 3 = sum, 4 = number).
You see it all depends on what is considered a variable.
I'm limping through a basic java class and have a really hard time thinking programmatic-ally so bear with me here. I'm supposed to write a program that sums all of the odd numbers in a user-defined range - simple right? Well I thought I had the code figured out to do it, but the math always comes in wrong. Instead of the range of 1 through 14 equaling 19 (1 + 3 + 5 ...), the program returns 46. It's only off by 3 so that makes me feel like I'm getting pretty close to correct code.
Here's the current sample output:
The value input is 14
DEBUG: The current value of variable sum is: 4
DEBUG: The current value of variable ctr is: 3
DEBUG: The current value of variable sum is: 10
DEBUG: The current value of variable ctr is: 7
DEBUG: The current value of variable sum is: 22
DEBUG: The current value of variable ctr is: 11
DEBUG: The current value of variable sum is: 46
DEBUG: The current value of variable ctr is: 15
The sum of the odd numbers from 1 to 14 is 46
Here's the troublesome method:
public static void calcSumPrint(int topEndNumber) {
//calc and print sum of the odd number from 1 to top-end number
//uses loop to add odd numbers
//display results: range (eg: 1 to 13), sum of odd numbers
for (ctr = 1; ctr <= topEndNumber; ctr = ctr + 2) {
nextOddNumber = sum + 2;
sum = sum + nextOddNumber;
ctr = ctr + 2;
if (debug) {
System.out.println("DEBUG: The current value of variable sum is: " + sum);
System.out.println("DEBUG: The current value of variable ctr is: " + ctr);
}
}
System.out.println("The sum of the odd numbers from 1 to " + topEndNumber + " is " + sum);
}//end of calcSumPrint
Here's the program:
import java.util.Scanner;
public class sumOdds {
static int topEndNumber = 0;
static int ctr = 0;
static int intermediateSum = 0;
static int sum = 1;
static boolean debug = true;
static int nextOddNumber = 0;
public static void main(String[] args) {
getLimitNumber();
System.out.println("The value input is " + topEndNumber);
calcSumPrint(topEndNumber);
}//end of main
public static int getLimitNumber() {
//lets uer input top-end number to be used in program [X]
//catches exception if non-integer value is used [X]
//verifies that the input number has a value of at least 1 [ ]
//returns verified int to method caller [ ]
Scanner input = new Scanner(System.in);
boolean done = false;
while (done != true) {
try {
System.out.println("Enter a positive whole top-end number to sum odds of:");
topEndNumber = input.nextInt();
if (topEndNumber <= 0){
throw new NumberFormatException();
}
done = true;
}//end of try
catch (Exception message) {
//put exception in here
input.nextLine();
System.out.println("Bad input, retry");
}//end of catch
}//end of while
input.close();
//to shut up eclipse
return topEndNumber;
}//end of getLimitNumber
public static void calcSumPrint(int topEndNumber) {
//calc and print sum of the odd number from 1 to top-end number
//uses loop to add odd numbers
//display results: range (eg: 1 to 13), sum of odd numbers
for (ctr = 1; ctr <= topEndNumber; ctr = ctr + 2) {
nextOddNumber = sum + 2;
sum = sum + nextOddNumber;
ctr = ctr + 2;
if (debug) {
System.out.println("DEBUG: The current value of variable sum is: " + sum);
System.out.println("DEBUG: The current value of variable ctr is: " + ctr);
}
}
System.out.println("The sum of the odd numbers from 1 to " + topEndNumber + " is " + sum);
}//end of calcSumPrint
public static int doAgain() {
//ask and verify the user wants to re-run program, return int
//to shut up eclipse
return 20000;
}//end of doAgain
}//end of class
Does anything jump out at you that I might be missing? I'd love to figure this one out and have been visualizing the algorithm on and off throughout the day at the office, it's driving me nuts that the math doesn't work out.
In your for loop the value of ctr is already incremented by two
so
sum = 0;
for (ctr = 1; ctr <= topEndNumber; ctr = ctr + 2) {
sum += ctr;
}
will give you the required answer.
I'm trying to find the factorial of 9 down to 0, only using one while loop, but my idea isn't outputting a value.
I figured out the way to do it using two while loops:
int i;
count = 9;
while (count >= 0){
value = count;
i = count-1;
while (i > 0){
value = value * i;
i--;
}
System.out.print(value + ", ");
}
This worked but I've tried to change it to use only one while loop and got this:
int i;
for (count = 9; count < 0; count--){
value = count;
i = count-1;
while (i > 0){
value = value * i;
i--;
}
System.out.print(value + ", ");
}
I'm not completely sure if I'm using the for statement correctly but I think I am, or at least I think it should output something so I can debug it.
Could someone give me a hint in the right direction?
This will give you all the factorials from 9 down to 1 :
int i=1;
int value=1;
String res = "";
while (i <= 9){
value = value * i;
res = value + ((i>1)?",":"") + res;
i++;
}
System.out.print(res);
Output :
362880,40320,5040,720,120,24,6,2,1
Perhaps it's cheating, since I'm calculating the factorials in ascending order from 1! to 9!, but I'm reversing the order of the output in order to get the required result.
Edit :
If you also want 0! to be printed, a small change can do the trick :
int i=1;
int value=1;
String res = "";
while (i <= 10){
res = value + ((i>1)?",":"") + res;
value = value * i;
i++;
}
System.out.print(res);
Output :
362880,40320,5040,720,120,24,6,2,1,1
First, the reason why your second loop doesn't work is that you have the wrong condition in the for. The condition in the middle is one that will cause the loop to continue, not to stop. So what you were saying was "start from 9, and work while the number is less than 0". But of course, your number is greater than zero to begin with.
Second, I believe using a for loop is a little bit of cheating, because a for loop is just a specific case of while loop.
Now to the problem of the factorial itself. You know that a factorial n! is defined as (n-1)!*n.
The basic loop for calculating one specific factorial is:
int n = 5;
int factorial = 1;
while ( n > 0 ) {
factorial *= n;
n--;
}
System.out.println( "Factorial is: " + factorial );
This will give you the factorial of five. But it's not exactly based on the formula we are talking about. There is another way to calculate it, starting from 1:
int n = 5;
int factorial = 1;
int count = 1;
while ( count <= n ) {
factorial *= count;
count++;
}
System.out.println( "Factorial is " + factorial );
The interesting part about this way of doing it is that in every stage of the loop, factorial is actually the value (count-1)! and we are multiplying it by count. This is exactly the formula we were talking about.
And the good thing about it is that just before you did it, you had the value of the previous factorial. So if you printed it then, there you'd get a list of all the factorials along the way. So here is a modified loop that prints all the factorials.
int n = 9;
int factorial = 1;
int count = 0;
while ( count < n ) {
System.out.println( "Factorial of " + count + " is " + factorial );
count++;
factorial *= count;
}
System.out.println( "Factorial of " + n + " is " + factorial );
Note that I modified it a little more so that it will work with zero. The factorial of zero is a special case so we shouldn't multiply by zero - that will make all the factorials wrong. So I changed the loop to multiply only after I increase count to 1. But this also means that you have to print the final factorial out of the loop.
Just first assign value=i, then run your loop. You can get the factorial with only while loop.
Important: Because n!=n*(n-1)!, therefore, i-- should must be perform before value = value * i.
public static void main(String args[]) {
int value=5;
int i=value;
while (i > 1){
i--;
value = value * i;
}
System.out.print(value);
}
Update: If you want to count factorial of 0 to 9, then use this code: (It includes factorial of 0 also)
public static void main(String args[]){
int countLowest=0;
int countHighest=9;
int value=1;
while (countLowest<= countHighest){
if(countLowest==0)
value = value * (countLowest+1);
else
value=value*countLowest;
countLowest++;
System.out.println("Factorial of "+(countLowest-1)+" is "+value);
}
}
Result:
Factorial of 0 is 1
Factorial of 1 is 1
Factorial of 2 is 2
Factorial of 3 is 6
Factorial of 4 is 24
Factorial of 5 is 120
Factorial of 6 is 720
Factorial of 7 is 5040
Factorial of 8 is 40320
Factorial of 9 is 362880
count = 9;
sum=1;
while (count >= 1){
sum*=count;
--count;
}
System.out.print(sum);
it will give you 9!=362880
I wrote a programm to get the cross sum of a number:
So when i type in 3457 for example it should output 3 + 4 + 5 + 7. But somehow my logik wont work. When i type in 68768 for example i get 6 + 0 + 7. But when i type in 97999 i get the correct output 9 + 7 + 9. I know that i have could do this task easily with diffrent methods but i tried to use loops . Here is my code: And thanks to all
import Prog1Tools.IOTools;
public class Aufgabe {
public static void main(String[] args){
System.out.print("Please type in a number: ");
int zahl = IOTools.readInteger();
int ten_thousand = 0;
int thousand = 0;
int hundret = 0;
for(int i = 0; i < 10; i++){
if((zahl / 10000) == i){
ten_thousand = i;
zahl = zahl - (ten_thousand * 10000);
}
for(int f = 0; f < 10; f++){
if((zahl / 1000) == f){
thousand = f;
zahl = zahl - (thousand * 1000);
}
for(int z = 0; z < 10; z++){
if((zahl / 100) == z){
hundret = z;
}
}
}
}
System.out.println( ten_thousand + " + " + thousand + " + " + hundret);
}
}
Is this what you want?
String s = Integer.toString(zahl);
for (int i = 0; i < s.length() - 1; i++) {
System.out.println(s.charAt(i) + " + ");
}
System.out.println(s.charAt(s.length()-1);
The problem with the code you've presented is that you have the inner loops nested. Instead, you should finish iterating over each loop before starting with the next one.
What's happening at the moment with 68768 is when the outer for loop gets to i=6, the ten_thousand term gets set to 6 and the inner loops proceed to the calculation of the 'thousand' and 'hundred' terms - and does set those as you expect (and leaving zahl equal to 768 - notice that you don't decrease zahl at the hundreds stage)
But then the outer loop continues looping, this time with i=7. With zahl=768, zahl/1000 = 0' so the 'thousand' term gets set to 0. The hundred term always gets reset to 7 with zahl=768.
The 97999 works because the thousand term is set on the final iteration of the 'i' loop, so never gets reset.
The remedy is to not nest the inner loops - and it'll perform a lot better too!
You should do something like this
input = 56789;
int sum = 0;
int remainder = input % 10 // = 9;
sum += remainder // now sum is sum + remainder
input /= 10; // this makes the input 5678
...
// repeat the process
To loop it, use a while loop instead of a for loop. This a great example of when to use a while loop. If this is for a class, it will show your understanding of when to use while loops: when the number of iterations is unknown, but is based on a condition.
int sum = 0;
while (input/10 != 0) {
int remainder = input % 10;
sum += remainder;
input /= 10;
}
// this is all you really need
Your sample is a little bit complicated. To extract the tenthousand, thousand and the hundreds you can simply do this:
private void testFunction(int zahl) {
int tenThousand = (zahl / 10000) % 10;
int thousand = (zahl / 1000) % 10;
int hundred = (zahl / 100) % 10;
System.out.println(tenThousand + "+" + thousand + "+" + hundred);
}
Bit as many devs reported you should convert it to string and process character by character.