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.

以上就是Binary to decimal conversion的详细内容,更多请关注web前端其它相关文章!

赞(0) 打赏
未经允许不得转载:web前端首页 » JavaScript 答疑

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

前端开发相关广告投放 更专业 更精准

联系我们

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

支付宝扫一扫打赏

微信扫一扫打赏