+ 1
Splitting integers
Hi everybody, I recently started learning Java (I've only completed the first chapter) and I wanted to practice a bit to impress better informations. I was thinking about how to split Integer number (with more than one digit) into single digit variables. For example, from "241" get single digits into three different variables like "2","4","1" and then make every single possible operation with them like 2+4, 2-4, 2*4 etc. Is there a way to do that or maybe I'm pushing over my small knowledge?
5 ответов
+ 4
There's ways to do just about anything.
Note* I'm not going to write all the code to spare the fun and practice. Though, I will tell you how to go about doing it.
You said you wanted them all to be separate variables, so you should use an array.
byte[] digits = new byte[3];
3 would just be from the length of the number inputted by the user. You can do a similar thing with division with what I'm about to tell you to find the length of a number. Or you can take the input as a string and use the strings .length() method. Then cast the String to an int.
You don't have to use a byte array here if you don't want to, just some optimization I always recommend.
Now we need to find some way to place each digit into the array.
We need to keep track of what index we are at in the array.
int index = 0;
Now how can we get each digit?
Lets say we have:
int input = 253;
As the users inputted number.
We need to grab it digit by digit.
I don't actually know the length of the number yet, this is because int is a primitive data-type, so it doesn't have any .length() method we can use.
Because of this I've chosen to use a while loop.
If you already found the length feel free to use a for loop and forget about the index variable. (You could use the for loops variable instead)
Back to the original question, how do we get each digit?
Well, we can use a combination of modulo and division.
What is 253 % 10?
That's right! it's 3!
That's the first digit!
Then, we can divide the number by 10.
Then take the modulo by 10 again to get the next digit.
All until the number is less than 1.
Add each digit to the array, and voila you have each digit. Don't forget to increment the index each time!
Another way would be to take the input as a String and convert each of its characters to a number, adding that to the array. That would be instead of using modulo and division.
+ 1
Really man...
+ 1
It's fine, but what does it has to have with my question?
+ 1
This might help.
https://code.sololearn.com/cOgvYRMLHhiW/?ref=app