简体   繁体   中英

Converting an integer and a character to a string in java

I'm trying to create a string comprised of a single letter, followed by 4 digits eg b6789. I'm getting stuck when I try to convert a character, and integer to one String. I can't use toString() because I've overwritten it, and I assume that concatenation is not the best way to approach it? This was my solution, until I realised that valueof() only takes a single parameter. Any suggestions? FYI - I'm using Random, because I will be creating multiples at some point. The rest of my code seemed irrelevant, and hence has been omitted.

   Random r = new Random();

   Integer numbers = r.nextInt(9000) + 1000;

   Character letter = (char)(r.nextInt(26) + 'a');

   String strRep = String.valueOf(letter, numbers);

I think they mean for you not to use concatenation with + operator.

Rather than that, there's a class called StringBuilder which will do the trick for you. Just create an empty one, append anything you need on it (takes Objects or primitives as arguments and does all the work for you), and at the end, just call at its "toString()" method, and you'll have your concatenated String.

For example

StringBuilder sb = new StringBuilder();
sb.append("Foo");
sb.append(123);
return sb.toString();

would return the string Foo123

you can use:

Character.toString(char)

which is

String.valueOf(char)

in reality which also works. or just use

String str = "" + 'a';

as already mentioned but not very efficient as it is

String str = new StringBuilder().append("").append('a').toString();

in reality.

same goes for integer + string or char + int to string. I think your simpliest way would be to use string concatenation

看起来像你想要的

String.valueOf(letter).concat(numbers.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