0% found this document useful (0 votes)
7 views2 pages

Number To Words

java code

Uploaded by

Linn Thành
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views2 pages

Number To Words

java code

Uploaded by

Linn Thành
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

public class NumberToWords {

private static final String[] BELOW_TWENTY = {"", "one", "two", "three",


"four", "five", "six", "seven", "eight", "nine",
"ten", "eleven", "twelve",
"thirteen", "fourteen", "fifteen", "sixteen",
"seventeen", "eighteen",
"nineteen"};
private static final String[] TENS = {"", "", "twenty", "thirty", "forty",
"fifty", "sixty", "seventy", "eighty", "ninety"};

public static void main(String[] args) {


// Manually handling input without using imports
System.out.println("Enter an integer between -999,999,999 and
999,999,999:");
int number = readInput();

// Convert the number to words and print it


System.out.println("In words: " + numberToWords(number));
}

// Method to read integer input without using Scanner or imports


public static int readInput() {
StringBuilder input = new StringBuilder();
char c;
boolean isNegative = false;

try {
while ((c = (char) System.in.read()) != '\n') {
if (c == '-') {
isNegative = true;
} else if (Character.isDigit(c)) {
input.append(c);
}
}
} catch (Exception e) {
System.out.println("Error reading input.");
}

// Convert input to integer


int number = Integer.parseInt(input.toString());
return isNegative ? -number : number;
}

public static String numberToWords(int num) {


if (num == 0) {
return "zero";
}

if (num < 0) {
return "negative " + numberToWords(-num);
}

return convert(num);
}

private static String convert(int num) {


if (num < 20) {
return BELOW_TWENTY[num];
} else if (num < 100) {
return TENS[num / 10] + ((num % 10 != 0) ? " " + BELOW_TWENTY[num % 10]
: "");
} else if (num < 1000) {
return BELOW_TWENTY[num / 100] + " hundred" + ((num % 100 != 0) ? " " +
convert(num % 100) : "");
} else if (num < 1000000) {
return convert(num / 1000) + " thousand" + ((num % 1000 != 0) ? " " +
convert(num % 1000) : "");
} else {
return convert(num / 1000000) + " million" + ((num % 1000000 != 0) ? "
" + convert(num % 1000000) : "");
}
}
}

You might also like