简体   繁体   中英

How to create a sequence of numbers in java

I want to create a sequence of numbers in Java like this :

1234957203969304597600234960702349100903450234847456282934857697900389262454869346

I want to create 1000 numbers in the sequence.

How can I do it?

I tried to do like this :

String seq = null;
for (int i = 0; i < 1000; i++) {
    seq = String.format("%d",i);
}
System.out.println(seq);

It does not work, it prints out:

999

StringBuilder sb = new StringBuilder();
for (int i=0; i<1000; i++) {
  sb.append(i);
}
System.out.println(sb.toString());

As a general note, while str = str + someString; will work, inside a loop it can quickly get out of hand. Try it with 10000 iterations and you'll see (large amounts of RAM & CPU consumed).

StringBuilder is better, if one really needs to build a string in this way, and it's always better performace-wise when one is appending to a character sequence more than a couple of times.

You need to append it to the String. I suggest using a StringBuilder.

What you are doing is overwriting the String every time

StringBuilder sb = new StringBuilder();
for(int i=0; i<1000; i++) {
    sb.append(Integer.toString(i);
}
System.out.println(sb.toString());

To make your code work, change seq=String.format("%d",i); into seq+=String.format("%d",i); .

A better way however, is to use a StringBuilder like this:

StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++){
    sb.append(i);
}
String seq = sb.toString();
System.out.println(seq);

EDIT: Actually, this doesn't generate a String with length 1000 , since it adds like this: 012345678910... (> 10 is two or three numbers instead of one).

So, instead try something like this using the Random class for a random number of 0-9 :

Random randomGenerator = new Random();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++){
    sb.append(randomGenerator.nextInt(9));
}
String seq = sb.toString();
System.out.println(seq);

如果你想创建一个长度为 1000 的流,每个数字都是随机的,那么试试 Math.random 函数。

Your code is printing 999 because you are always overwriting the string with the last value of the loop , you need to append the data, not overwrite it over and over again...

Example:

StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++) {
    sb.append(i);
}
System.out.println(sb.toString());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM