How to do that,
When user inputs n=4
then it should generate a string like str="1234"
?
Asked
Active
Viewed 134 times
0

Youcef LAIDANI
- 55,661
- 15
- 90
- 140

Abhishec Kumar
- 105
- 1
- 10
-
for (int i = 1; i <= 4; i++) { string+=i; } – JYoThI Apr 29 '17 at 08:59
3 Answers
5
You can use a simple loop for example :
int n = 4;
String str = "";
for (int i = 1; i <= n; i++) {
str+=i;
}
can we directly get int= 1234
In this case you can parse it like this :
int result = Integer.parseInt(str);
If you want to avoid this and get int
from the begging you can use :
int n = 4;
int result = 0;
for (int i = 1; i <= n; i++) {
result *= 10;
result += i;
}

Youcef LAIDANI
- 55,661
- 15
- 90
- 140
5
int n = 10;
StringBuffer s = new StringBuffer();
for(int i=1;i<=n;i++){
s = s.append(i);
}
System.out.println(s.toString());

Rahul Rabhadiya
- 430
- 5
- 19
1
Note: Do not use String concatenation in for, instead it use StringBuilder.
Take a look at this question.
In your case n
is a small value and because it is not so important. If n
has a big value it will be a vast of memory.
Java 8 way
int n = 4;
StringBuilder sb = new StringBuilder();
IntStream.rangeClosed(1, n).forEach(sb::append);
String str = sb.toString();
Java 7 way
int n = 4;
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= n; i++) {
sb.append(i);
}
String str = sb.toString();