Java Exercises: Transform a given integer to String format
Java Basic: Exercise-166 with Solution
Write a Java program to transform a given integer to String format.
Pictorial Presentation:
Sample Solution:
Java Code:
import java.util.*;
public class Solution {
public static String transform_int_to_string(int n) {
boolean is_negative = false;
StringBuilder tsb = new StringBuilder();
if (n == 0) {
return "0";
} else if (n < 0) {
is_negative = true;
}
n = Math.abs(n);
while (n > 0) {
tsb.append(n % 10);
n /= 10;
}
if (is_negative) {
tsb.append("-");
}
return tsb.reverse().toString();
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Input an integer: ");
int n = in.nextInt();
System.out.println("String format of the said integer: " + transform_int_to_string(n));
}
}
Sample Output:
Input an integer: 35 String format of the said integer: 35
Flowchart:
Java Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a Java program to move every positive number to the right and every negative number to the left of a given array of integers.
Next: Write a Java program to move every zero to the right side of a given array of integers.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
Java: Tips of the Day
How to sort an ArrayList?
Collections.sort(testList); Collections.reverse(testList);
That will do what you want. Remember to import Collections though!
Ref: https://bit.ly/32urdSe
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework