Advertisement
Guest User

Untitled

a guest
Feb 20th, 2019
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.37 KB | None | 0 0
  1. import java.util.Scanner;
  2. import java.util.*;
  3. import java.lang.Math;
  4.  
  5. public class BinaryToDecimal {
  6. public static void main(String[] args) {
  7. Scanner in = new Scanner(System.in);
  8. 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");
  9. String bin = in.nextLine();
  10. String bin2 = bin.toLowerCase();
  11. int len = bin2.length();
  12. int len2 = len;
  13. int dec = 0;
  14.  
  15. while (len == 0){System.out.println("Nothing was inputted, please input either 'quit' or a binary number");
  16. bin2 = in.nextLine();}
  17.  
  18. if (bin2.indexOf("quit") > -1 && len == 4){
  19. return;}
  20.  
  21. while (bin2.indexOf("quit") > -1 && len != 4)
  22. {System.out.println("Input can't have letters besides specifically entering the word 'quit' to exit the program");
  23. bin2 = in.nextLine();}
  24.  
  25. if (bin2.indexOf("quit") == -1){
  26. if (bin2.matches("\\d[01]+") || bin2.equals("1") || bin2.equals("0")) {
  27. do {
  28. dec += ((bin2.charAt(len-len2))*((int)Math.pow(2, (len2 - 1))));
  29. len2--;
  30. } while (len2 != 0);
  31. System.out.println(bin2);
  32. System.out.println(dec);
  33. }
  34. else if (!bin2.matches("\\d[01]+")) {
  35. 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");
  36. bin2 = in.nextLine();}
  37. }
  38. }
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement