Question: I need help with some code to validate user input of only 1s and 0s for this program to convert binary to decimal format. If

I need help with some code to validate user input of only 1s and 0s for this program to convert binary to decimal format. If the user enters a non binary number it outputs 0.0 and if there are any 1s and/or 0s it will read them from the string and still do the math, ie: 512 will still output 2.0. My code so far is listed below. This is a java program.

import java.util.Scanner;

public class Main {

public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter binary string: "); String binary = sc.next(); double decimal = 0; for(int i = 0; i < binary.length(); i++){ if(binary.charAt(i) == '1'){ decimal = decimal + Math.pow(2, binary.length()-1-i); }

} System.out.println("The binary number "+ binary + " is: "+ decimal); } }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!