Ask your own question, for FREE!
Computer Science 9 Online
OpenStudy (pottersheep):

Changing a string into integer in Java help PLEASE !!!!!!

OpenStudy (pottersheep):

This is my code: import java.util.Scanner; public class DecimalToBinaryConverter { public static void main(String[] args) { Scanner in = new Scanner(System.in); int decimalNumber; String binaryNumber; System.out.print("Enter decimal # "); decimalNumber = in.nextInt(); binaryNumber = ""; while (decimalNumber != 0) { // add spaces to separate 4-digit groups if (binaryNumber.length() % 5 == 0) binaryNumber = " " + binaryNumber; // extract last number o binaryy binaryNumber = (decimalNumber % 2) + binaryNumber; // cut last digit in binary representation decimalNumber /= 2; } System.out.println("Binary: " + binaryNumber); int bin = Integer.parseInt(binaryNumber); System.out.print ("hi" + bin); } }

OpenStudy (pottersheep):

I want to vhange the value of binaryNumber into an integer....and I did so by doing this int bin = Integer.parseInt(binaryNumber); but it keeps showing error and won't print it........WHYWHYWHY :(

OpenStudy (pottersheep):

My code is changing a decimal number into a binary number by the way

OpenStudy (pottersheep):

Everything about the code is fine up to there btw

OpenStudy (asnaseer):

I think you need to also tell it that your number is in binary, so use: Integer.parseInt(binaryNumber, 2)

OpenStudy (asnaseer):

the 2nd parameter tells it that you have a number in base 2

OpenStudy (pottersheep):

Really? Oh thanks! I'll try that!! Thank you!!

OpenStudy (asnaseer):

yw

OpenStudy (pottersheep):

It didn't work ..... hmmm

OpenStudy (asnaseer):

can you tell me what is in your string binaryNumber?

OpenStudy (asnaseer):

ok - looks like you have embedded spaces in binaryNumber - you need to strip those before converting to Integer

OpenStudy (asnaseer):

Integer.parseInt(binaryNumber.replace(" ", ""), 2)

OpenStudy (pottersheep):

*headdesk* thanks again!

OpenStudy (asnaseer):

:) yw

OpenStudy (pottersheep):

It worked!!!!! <333333

OpenStudy (s3a):

public class ConvertIntToString { public static void main(String[] args) { int aInt = 1; String aString = Integer.toString(aInt); // or String anotherString = "" + aInt; } }

OpenStudy (rsmith6559):

pottersheep, you may want to think about doing the number->string conversion recursively.

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!