Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- import java.util.*;
- import java.lang.Math;
- public class BinaryToDecimal {
- public static void main(String[] args) {
- Scanner in = new Scanner(System.in);
- System.out.println("Please enter either a binary number as a sequence of 1's and 0's or type 'quit' to exit the program");
- String bin = in.nextLine();
- String bin2 = bin.toLowerCase();
- int len = bin2.length();
- int len2 = len;
- int dec = 0;
- while (len == 0){System.out.println("Nothing was inputted, please input either 'quit' or a binary number");
- bin2 = in.nextLine();}
- if (bin2.indexOf("quit") > -1 && len == 4){
- return;}
- while (bin2.indexOf("quit") > -1 && len != 4)
- {System.out.println("Input can't have letters besides specifically entering the word 'quit' to exit the program");
- bin2 = in.nextLine();}
- if (bin2.indexOf("quit") == -1){
- if (bin2.matches("\\d[01]+") || bin2.equals("1") || bin2.equals("0")) {
- do {
- dec += ((bin2.charAt(len-len2))*((int)Math.pow(2, (len2 - 1))));
- len2--;
- } while (len2 != 0);
- System.out.println(bin2);
- System.out.println(dec);
- }
- else if (!bin2.matches("\\d[01]+")) {
- System.out.println("Input can't have numbers besides 1 and 0, or any letters if you have not decided to exit with the 'quit' command");
- bin2 = in.nextLine();}
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement