import java.util.Scanner; class Atof { /* --- parseFloat(s): Ascii to float conversion function --- */ public static float myParseFloat(String s) { float value; // Return value int k, sign, pos; /* ------- Check for negative sign ------- */ if (s.charAt(0) == '-') { sign = -1; pos = 1; // Start at digit s.charAt(1) } else { sign = 1; pos = 0; // Start at digit s.charAt(0) } /* ------------------------------------------ Convert the whole number part first ------------------------------------------ */ value = 0; for (k = pos; k < s.length(); k++) { /* ==================================== Stop when you see a decimal point ==================================== */ if ( s.charAt(k) == '.' ) { pos = k+1; break; } value = (float) (10*value + ( s.charAt(k) - 48 )); } /* ------------------------------------------ Convert the fractional part next ------------------------------------------ */ if ( k < s.length() ) { float f = 10.0f; for (k = pos; k < s.length(); k++) { value = (float) (value + ( s.charAt(k) - 48 )/f); f = f * 10.0f; } } /* ======================================================== Negate 2's complement representation if first character of input was '-' ========================================================= */ if (sign == -1) value = -value; // Compute the negative value (flip bits and add 1 !!) return(value); // Return a BINARY 2's compl code } public static void main(String[] args) { Scanner in = new Scanner(System.in); String s1, s2; float f1, f2; System.out.print("Enter an float (string) s1: "); s1 = in.next(); System.out.println("We read the numeric string: \"" + s1 + "\""); f1 = myParseFloat(s1); // System.out.println("The float VALUE for this numeric string is: " + f1); System.out.print("\nEnter another float (string) s2: "); s2 = in.next(); System.out.println("We read the numeric string: \"" + s2 + "\""); f2 = myParseFloat(s2); // System.out.println("The float VALUE for this numeric string is: " + f2); System.out.println("==================================================="); System.out.println("The sum of the integer values = " + (f1+f2) ); } }