Java: Convert 3 digits positive number in given format
Java Basic: Exercise-246 with Solution
Let us use the letter H to mean "hundred", the letter T to mean "ten" and “1, 2, . . . n” to represent the one digit n (<10). Using the given format, write a Java program that converts 3 digits positive numbers. For example, 234 should be output as BBSSS1234 because it has 2 "hundreds", 3 "ten", and 4 ones.
Input:
235
230
Output:
HHTTT12345
HHTTT
Sample Solution:
Java Code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Input a positive number(max three digits):");
char[] num = String.format("%03d", in.nextInt()).toCharArray();
StringBuilder tm = new StringBuilder();
for (int i = 0; i < num[0] - '0'; i++) {
tm.append("H");
}
for (int i = 0; i < num[1] - '0'; i++) {
tm.append("T");
}
for (int i = 0; i < num[2] - '0'; i++) {
tm.append(i + 1);
}
System.out.println("Result:");
System.out.println(tm.toString());
}
}
Sample Output:
Input a positive number(max three digits): 235 Result: HHTTT12345
Pictorial Presentation:
Flowchart:

Java Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a Java program which accepts students name, id, and marks and display the highest score and the lowest score.
Next: Write a Java program which accepts three integers and check whether sum of the first two given integers is greater than third one. Three integers are in the interval [-231, 231 ].
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join