Advertisement
brilliant_moves

BooleanComplementer.java

May 6th, 2020
1,924
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.09 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class BooleanComplementer {
  4.  
  5.     /*
  6.        Takes a string as in input and returns a string with a boolean complement
  7.        of each digit except the last one. Example: 11101 returns 00011
  8.     */
  9.     public static String getComplement (String inp) {
  10.         String ans = "";
  11.         // loop through each character of inp
  12.         for (int i=0; i<inp.length(); i++) {
  13.             if (!(inp.substring(i, i+1).equals("1") || inp.substring(i, i+1).equals("0"))) {
  14.                 System.out.println ("Not a binary string!");
  15.                 ans = "-1";
  16.                 break;
  17.             }
  18.             if (i<inp.length()-1) {
  19.                 // when input character is 1, add 0 and vice versa
  20.                 ans += (inp.substring(i, i+1).equals("1")? "0": "1");
  21.             } else {
  22.                 // last digit remains unchanged
  23.                 ans += inp.substring(i, i+1);
  24.             }
  25.         }
  26.         return ans;
  27.     }
  28.  
  29.     public static void main (String[] args) {
  30.         Scanner in = new Scanner (System.in);
  31.         String input, answer;
  32.         System.out.print ("Enter boolean string: ");
  33.         input = in.nextLine();
  34.         answer = getComplement (input);
  35.         if (!answer.equals ("-1")) {
  36.             System.out.println ("Answer: " + answer);
  37.         }
  38.     }
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement