This site requires JavaScript, please enable it in your browser!
Greenfoot back
sengst
sengst wrote ...

2014/8/22

Is there a way to combine ints

sengst sengst

2014/8/22

#
Hello. I was wondering if there is a way to combine ints. No like adding them, but 7 and 8 = 78. Thanks. By the way, I'm not sure what this is supposed to be...
danpost danpost

2014/8/22

#
If the combined value is not important, then:
String combinedInts = ""+(7)+(8);
If you need the resultant value, then use this:
int combinedInts = Integer.parseInt(""+(7)+(8));
Super_Hippo Super_Hippo

2014/8/22

#
Are you programming a calculator? There, the second number is always a digit. Then the displayed number is the old number * 10 + the new number. For example as default there is a 0. You press 5. 0*10+5=5 is displayed. Then you press a 7. 5*10+7=57 is displayed. If you want any numbers to be added together like this, you first have to check how long your second number is. So if it is between 10 and 99, you have to multiply the first number with 100 instead of 10 before adding the second one. To code this, you can either do an if-else which could be quite long if you want to do it for any numbers, or do something like this.
//current = the current number
//newNum = the new number which is "added" at the end of the current number
int multiplier = 1;
while(true)
{
    if (Math.pow(10,multiplier) > newNum) break;
    else multiplier++;
}
current = current*Math.pow(10,multiplier)+newNum;
Well, I did not tested this, but this is how I would try to do it. Edit: Looks like danpost has an easier solution. ;)
sengst sengst

2014/8/22

#
Thank you! You've been a great help! Thanks again. Both of you!
You need to login to post a reply.