Advertisement
chaibs

loop-hw4

Dec 27th, 2017
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.08 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class hw4 {
  4.  
  5.     public static void main(String[] args) {
  6.         int bin = 0, newNum = 0, temp = 0, flag = 0;
  7.  
  8.         Scanner s = new Scanner(System.in);
  9.  
  10.         System.out.println("Please enter a binary number:");
  11.         bin = s.nextInt();// getting number from user
  12.         temp = bin;// saving in temp for checking
  13.  
  14.         while (temp > 0) {// as long as the number bigger then 0 continue
  15.             if (temp % 10 != 1 && temp % 10 != 0) {// checking if the number is not binary
  16.                 System.out.println("Not a binary number");// result if number is not binary
  17.                 temp = 0;// closing the while loop
  18.                 flag = 1;// flag for ending program
  19.             }
  20.             temp /= 10;// removing the rightist number
  21.         }
  22.  
  23.         if (flag == 0) {// checking if flag is not ending program
  24.             for (int i = 1; bin > 0; i *= 2) {// loop for power number and as long as the binary number is not 0
  25.                 newNum += (bin % 10) * i;// multiplying in the index, the index is the power number
  26.                 bin /= 10;// removing the rightist number
  27.             }
  28.             System.out.println("The decimal number is: " + newNum);// result
  29.         }
  30.     }
  31.  
  32. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement