0

I am kind of confused is my program correct or I am missing something!

I could get an output out of it.

public static void main(String args[]) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter you String: ");
    String bin = sc.nextLine();

    int length = bin.length();
    int j = 0;
    int sum = 0;

    if (length != 0) {
        for (int i = length - 1; i >= 0; i--) {
            if (bin.charAt(i) == "0" || bin.charAt(i) == "1") {
                String s = bin.charAt(j) + "";
                sum = (int) (sum + (Integer.valueOf(s)) * (Math.pow(2, i)));
                j++;
            } else {
                System.out.println("illegal input.");
            }
        }
        System.out.println(sum);
    } else {
        System.out.println("illegal input.");

    }
}
1
  • 2
    You mean if (bin.charAt(i) == '0' || bin.charAt(i) == '1') { note the single quote ' Commented Jun 30, 2018 at 21:33

1 Answer 1

1

Remove the quotation marks on this line:

if (bin.charAt(i) == "0" || bin.charAt(i) == "1") {

should become

if (bin.charAt(i) == 0 || bin.charAt(i) == 1) {

Below code works fine:

import java.util.Scanner;

public class test {
public static void main (String args []) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter you String: ");
    String  bin = sc.nextLine();

    int length = bin.length();
    int j = 0;
    int sum = 0;

    if (length != 0) {
        for (int i = length - 1; i >= 0; i--) {
            if (bin.charAt(i) == '0' || bin.charAt(i) == '1') {
                String s = bin.charAt(j) + "";
                sum = (int) (sum + (Integer.valueOf(s)) * (Math.pow(2, i)));
                j++;
            } else {
                System.out.println("illegal input.");
            }
        }
        System.out.println(sum);
    } else {
        System.out.println("illegal input.");

    }
}
}
Sign up to request clarification or add additional context in comments.

8 Comments

i fixed that part but the program still throws me an error on import java.util.*;
You need single quotes: 0 should be '0', and the same for 1.
consecutive statement on line must be separated by ';'
and on " public static void main (String args []) {" statement ==exception declaration
What error does it throw? It works fine for me for the inputs "0123456" and "kaan" :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.