Changing a string into integer in Java help PLEASE !!!!!!
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); } }
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 :(
My code is changing a decimal number into a binary number by the way
Everything about the code is fine up to there btw
I think you need to also tell it that your number is in binary, so use: Integer.parseInt(binaryNumber, 2)
the 2nd parameter tells it that you have a number in base 2
Really? Oh thanks! I'll try that!! Thank you!!
yw
It didn't work ..... hmmm
can you tell me what is in your string binaryNumber?
ok - looks like you have embedded spaces in binaryNumber - you need to strip those before converting to Integer
Integer.parseInt(binaryNumber.replace(" ", ""), 2)
*headdesk* thanks again!
:) yw
It worked!!!!! <333333
public class ConvertIntToString { public static void main(String[] args) { int aInt = 1; String aString = Integer.toString(aInt); // or String anotherString = "" + aInt; } }
pottersheep, you may want to think about doing the number->string conversion recursively.
Join our real-time social learning platform and learn together with your friends!