Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- public class hw4 {
- public static void main(String[] args) {
- int bin = 0, newNum = 0, temp = 0, flag = 0;
- Scanner s = new Scanner(System.in);
- System.out.println("Please enter a binary number:");
- bin = s.nextInt();// getting number from user
- temp = bin;// saving in temp for checking
- while (temp > 0) {// as long as the number bigger then 0 continue
- if (temp % 10 != 1 && temp % 10 != 0) {// checking if the number is not binary
- System.out.println("Not a binary number");// result if number is not binary
- temp = 0;// closing the while loop
- flag = 1;// flag for ending program
- }
- temp /= 10;// removing the rightist number
- }
- if (flag == 0) {// checking if flag is not ending program
- for (int i = 1; bin > 0; i *= 2) {// loop for power number and as long as the binary number is not 0
- newNum += (bin % 10) * i;// multiplying in the index, the index is the power number
- bin /= 10;// removing the rightist number
- }
- System.out.println("The decimal number is: " + newNum);// result
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement