0

I want to write a program which receive a string value and print the decimal number.

In addition, if the string value is not 1 or 0, I need to print a message.

I wrote this code but it is always getting inside the if command.

I Would appreciate your support!

Thank you

import java.util.Random; 
public class Decimal {

    public static void main(String[] args) {
        String input = (args[0]);
        int sum = 0;
        for (int i = 0; i <= input.length(); i++) {
            if (!(input.charAt(i) == '0') || (input.charAt(i) == '1')) {
                System.out.println("wrong string");
                break;
            }
            char a = input.charAt(i);
            if (a == '1') {
                sum |= 0x01;
            }
            sum <<= 1;
            sum >>= 1;
            System.out.println(sum);
        }
    }
}
6
  • change !(input.charAt(i) == '0') || (input.charAt(i) == '1') to !(input.charAt(i) == '0') && (input.charAt(i) == '1') Commented Nov 6, 2015 at 15:12
  • And that would still be wrong with the parens placed like that. Commented Nov 6, 2015 at 15:13
  • Rather sth like (!(input.charAt(i) == '0' || input.charAt(i) == '1')) Commented Nov 6, 2015 at 15:14
  • JackWilliams, I've changed it. Commented Nov 6, 2015 at 15:17
  • SBI - so what do you recommend please? Commented Nov 6, 2015 at 15:17

1 Answer 1

1

The ! (not) operator of the if statement only applies to the first part:

if ( ! (input.charAt(i) == '0')
     ||
     (input.charAt(i) == '1')
   ) {

So that is the same as:

if ((input.charAt(i) != '0') || (input.charAt(i) == '1')) {

When you actually meant to do:

if (input.charAt(i) != '0' && input.charAt(i) != '1') {

It's a good thing though, because once that works, you're going to get an IndexOutOfBoundsException when i == input.length(). Change the loop to:

for (int i = 0; i < input.length(); i++) {

And for performance, move variable a up and use it in that first if statement. Rename to c or ch is more descriptive/common.

Doing both sum <<= 1 and sum >>= 1 leaves you where you started. Is that what you wanted? You should also do the left-shift before setting the right-most bit.

Applying all that, I believe you meant to do this:

String input = args[0];
int sum = 0;
for (int i = 0; i < input.length(); i++) {
    char c = input.charAt(i);
    if (c != '0' && c != '1') {
        System.out.println("wrong string");
        break;
    }
    sum <<= 1;
    if (c == '1')
        sum |= 1;
}
System.out.println(sum);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.