// // File: /home/cs255001/demo/atoi/ConvInt1DigitNeg.java // // Converting a binary number between [-9 .. 9] to a String // public class ConvInt1DigitNeg { public static void main(String[] args) throws Exception { int x, sign = 0; char[] c = new char[1]; // char array of size 1 // (because we only have 1 character) x = -7 ; // Change to any value between 0 and 9 // *** If you use x = 10, program will print : // *** Can you figure out WHY ??? // +++ Try negative numbers if ( x < 0 ) { sign = -1; x = -x; // x >= 0 ! } else sign = 0; c[0] = (char) (x + 48); // c is equal to ASCII code for the number ! /* --------------------------------------------- Make a string out of the character(s) ---------------------------------------------- */ String s = new String(c); if ( sign == -1 ) s = "-" + s; // Add neg sign before number System.out.println(">>> " + s); } }