how to take binary input in java

‮/:sptth‬/www.lautturi.com
how to take binary input in java

To take binary input in Java, you can use the Scanner class and the nextInt method to read an integer value from the standard input, and then use the Integer.toBinaryString method to convert the integer to a binary string.

Here's an example of how you can do this:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Read an integer value from the standard input
        int num = scanner.nextInt();

        // Convert the integer to a binary string
        String binary = Integer.toBinaryString(num);

        System.out.println("Binary representation: " + binary);
    }
}

This code will read an integer value from the standard input, convert it to a binary string, and print the binary string to the console.

Note that the nextInt method will only read an integer value from the input, and will not read any leading or trailing characters that are not part of the integer. If you want to read a binary string from the input, you can use the next method to read the entire input as a string, and then use the parseInt method to parse the binary string.

Here's an example of how you can do this:

Scanner scanner = new Scanner(System.in);

// Read the entire input as a string
String input = scanner.next();

// Parse the binary string to an integer
int num = Integer.parseInt(input, 2);

System.out.println("Integer value: " + num);

This code will read a binary string from the standard input, parse it to an integer, and print the integer value to the console.

Note that the parseInt method expects the input string to be a valid binary string, and will throw a NumberFormatException if the input string is not a valid binary string. You can use a try-catch block to handle the exception if necessary.

Created Time:2017-11-01 20:43:02  Author:lautturi