Alright, so I am building a Converter to convert ASCII to Binary and for some reason, the for each loop stops working when it hits a space, and I have no idea why. I'm probably just over thinking it.
Extra: Can you tell me how to force the output binary to be 8 chars? So add 0's to the front until the length is 8.
package com.github.geodox.asciitobinary.main;
import java.util.Scanner;
public class ASCIItoBinary
{
private static Scanner input = new Scanner(System.in);
public static void main(String[] args)
{
getInput();
}
private static void getInput()
{
String repChar;
String inputString;
log("Please Enter a Character to Represent a Space: ");
repChar = input.next();
if(repChar.length() < 1 | repChar.length() > 1)
{
logln("Character Length is invalid. Please Enter a Single Character.");
getInput();
}
log("Please Enter a String to convert to Binary: ");
inputString = input.next();
convertToBinary(repChar, inputString);
}
private static void convertToBinary(String repChar, String inputString)
{
String outputString = "";
for(char c : inputString.toCharArray())
{
if(c != ' ')
{
outputString = outputString + " " + Integer.toBinaryString((int) c);
}
else
{
outputString = outputString + " " + repChar;
}
}
outputString = outputString.trim();
outputBinary(outputString);
}
private static void outputBinary(String outputString)
{
log(outputString);
}
public static void log(Object aObject)
{
System.out.print(aObject);
}
public static void logln(Object aObject)
{
System.out.println(aObject);
}
}