Advertisement
Guest User

Untitled

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