PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, August 11, 2022

[FIXED] How to put numbers to array in while loop in java?

 August 11, 2022     binary, decimal, java     No comments   

Issue

I am trying to add two binary numbers and then get their sum in binary system. I got their sum in decimal and now I am trying to turn it into binary. But there is problem that when I take their sum (in decimal) and divide by 2 and find remainders(in while loop), I need to put remainders into array in order print its reverse. However, there is an error in array part. Do you have any suggestions with my code? Thanks in advance.

Here is my code:

import java.util.Scanner;

public class ex1 {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        int m = scan.nextInt();
        int k = dec1(n)+dec2(m);

        int i=0,c;
            int[] arr= {};

        while(k>0) {
            c = k % 2;
        k = k / 2;
                arr[i++]=c;   //The problem is here. It shows some //error
        }
          while (i >= 0) {
        System.out.print(arr[i--]);
        }
    }

    public static int dec1(int n) {
        int a,i=0;
        int dec1 = 0;
        while(n>0) {
        a=n%10;
        n=n/10;
        dec1= dec1 + (int) (a * Math.pow(2, i));
        i++;
        }
        return dec1;
    }

    public static int dec2(int m) {
        int b,j=0;
        int dec2 = 0;
        while(m>0) {
        b=m%10;
        m=m/10;
        dec2= dec2 + (int) (b  * Math.pow(2, j));
        j++;    
        }
        return dec2;
        }


}

Solution

Why are you using two different methods to do the same conversion? All you need is one.

You could have done this in the main method.

 int k = dec1(n)+dec1(m);

Instead of using Math.pow which returns a double and needs to be cast, another alternative is the following:

      int dec = 0;
      int mult = 1;
      int bin = 10110110; // 128 + 48 + 6 = 182.
      while (bin > 0) {
         // get the right most bit
         int bit = (bin % 10);

         // validate
         if (bit < 0 || bit > 1) {
            throw new IllegalArgumentException("Not a binary number");
         }

         // Sum up each product, multiplied by a running power of 2.
         // this is required since bits are taken from the right.
         dec = dec + mult * bit;
         bin /= 10;
         mult *= 2; // next power of 2
      }
      System.out.println(dec); // prints 182

An alternative to that is to use a String to represent the binary number and take the bits from the left (high order position).

      String bin1 = "10110110";
      int dec1 = 0;
      // Iterate over the characters, left to right (high to low)
      for (char b : bin1.toCharArray()) {

         // convert to a integer by subtracting off character '0'.
         int bit = b - '0';

         // validate
         if (bit < 0 || bit > 1) {
            throw new IllegalArgumentException("Not a binary number");
         }
         // going left to right, first multiply by 2 and then add the bit
         // Each time thru, the sum will be multiplied by 2 which shifts everything left
         // one bit.
         dec1 = dec1 * 2 + bit;
      }

      System.out.println(dec1); // prints 182

One possible way to display the result in binary is to use a StringBuilder and simply insert the converted bits to characters.

  public static String toBin(int dec) {
      StringBuilder sb = new StringBuilder();

      while (dec > 0) {
         // by inserting at 0, the bits end up in
         // correct order.  Adding '0' to the low order
         // bit of dec converts to a character.
         sb.insert(0, (char) ((dec & 1) + '0'));

         // shift right for next bit to convert.
         dec >>= 1;
      }
      return sb.toString();
   }


Answered By - WJS
Answer Checked By - Robin (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing