# Binary to decimal conversion

I am a novice programmer trying to write a program that converts an entered Binary number into a decimal number. As far as I can tell, the math and code are right, and no compilation errors are returned, however the number that is output is NOT the correct decimal number. My code is as follows: String num; double result = 0; do { Scanner in = new Scanner(System.in); System.out.println("Please enter a binary number or enter 'quit' to quit: "); num = in.nextLine(); int l = num.length(); if (num.indexOf("0")==-1 || num.indexOf("1")==-1 ){ System.out.println("You did not enter a binary number."); } for (int i = 0; i < l; i++) { result = result + (num.charAt(i) * Math.pow(2, (l - i))); } System.out.println("The resulting decimal number is: " +result); } while (!num.equals("quit")); if (num.equals("quit")){ System.out.println("You chose to exit the program."); return; } Any Help you could give would be much appreciated. I tried making my question as clear as possible but if you have any questions I will try to answer the best I can. I have not been doing this long. All I need is for someone to look it over and hopefully find the error I made somewhere, thanks.
If this weren't a programming exercise, you could use Long.parseLong(String s, int radix) with a radix of 2.

### 觉得文章有用就打赏一下文章作者

#### 支付宝扫一扫打赏 #### 微信扫一扫打赏 