Java - Integers and Binaries

Akenaten :

Trying to create a program where you input binary numbers, and you get the sum of these two again in binary form. Why doesn't the code work;

import java.util.Scanner;
   class ABC{
      public static void main(String[] args){
        Scanner toy = new Scanner(System.in);
        int x = toy.nextInt();
        int y = toy.nextInt();
        x = 0bx; y=0by; ------------> ERROR SHOWS UP
        int z = x + y;
        System.out.println(Integer.toBinaryString(z));
        }
     }

The error message reads:

binary numbers must contain at least one binary digit 
';' expected

Ideal example:

x = 101 (integer) --> x = 5 (binary meaning of 101)
y = 10  (integer) --> y = 2 (binary meaning of 10)
z = x + y = 5 + 2 = 7
return binary form of 7 (111)
Roland Illig :

You wrote 0bx, which were a nice programming trick if it worked. It doesn't, as you experienced yourself.

To see why, you need to know that the code you wrote is first interpreted as a whole, and is translated by the compiler into a program in machine code. In principle the compiler could figure out what you were trying to say with the 0bx expression. It's just that the Java programming language doesn't allow this expression.

It says something similar to:

A binary literal is written by 0b, followed by only 0 and 1, at least one and as many as possible.

The word literal means something related to letters, "as written". Therefore you cannot use this part of the programming language.

But there's another part. The method Integer.parseInt has 2 variants: Integer.parseInt("12345") converts a decimal representation of the number into that number. The variant Integer.parseInt("101110101101", 2) parses a binary representation of a number into that number.

If there is a method toy.nextInt(2), you can use that. Otherwise you have to use Integer.parseInt(toy.next(), 2).

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=143675&siteId=1