This discussion is archived
7 Replies Latest reply: Dec 30, 2007 7:59 AM by 800282 RSS

Convert binary String to One Complement.

807601 Newbie
Currently Being Moderated
Hi All,

this is my first post on here, as I'm really new to Java. I'm first year University in Bradford, England.

Anyways, I've really been struggling with trying to write a program which will convert any binary String to the One's Complement of that String (for anyone who doesn't know, this simply means changing any '1' to '0' and vice versa, ie "110011" would become "001100" etc...(excuse my immense patronising)) I've tried about 6/7 different ways, all the programs compile and run, but never give me the result I want.

My latest attempt is as follows:
import java.util.*;
import java.lang.*;

public class OneComplement2 {

    public static void main (String [] args) {
        
        String a = "1";
        String b = "0"; 
        
        Scanner reader = new Scanner(System.in);
        String binary; 
        String binary2; 
//        int i=0; 
        
        System.out.println("Enter a binary number:");
        binary = reader.nextLine(); 
        
//      public String replaceAll(String regex,
//      String replacement)
       
        binary2 = binary.replaceAll(a, b);// binary2 = binary.replaceAll(b, a);
       
        System.out.println(binary2);
    
    }
    
}
I'm stumped guys. Any help would be much appreciated.

Cheers,

later,

Aaron.