Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Convert binary String to One Complement.

807601Dec 30 2007 — edited Dec 30 2007
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.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jan 27 2008
Added on Dec 30 2007
7 comments
2,097 views