0

I want to make a code wich reads from the keyboard a character and that character i want to add it to a string variable

Example

char c = sc.next().charAt(0);
String l = "";

[my character from keyboard beeing now in "c" and "l" beeing empty]

How can i make "l" to add to it's value the character from "c"

I want to make that "l" to stock all the char introduced so it needs to concatenate "l" with "c"...

4 Answers4

0

You can use

String l = "";
char c = sc.next().charAt(0);
l = l + String.valueOf(c);

Or,

StringBuilder sbuilder = new StringBuilder();
char c = sc.next().charAt(0);
sBuilder.append(String.valueOf(c));
String l = sBuilder.toString();
Vishal K
  • 12,976
  • 2
  • 27
  • 38
0

You want a StringBuilder object, to which you can append char characters, then you convert it to a String with toString().

rgettman
  • 176,041
  • 30
  • 275
  • 357
0

Use a StringBuilder. It has a append(char c) method to do exactly what you want.

Also, at the end of processing you can use its toString method to get the equivalent String object.

0
 Scanner sc = new Scanner(System.in);
 char c = sc.next().charAt(0);
 String l = "";
 l=l+c;
 System.out.println(l);
Alya'a Gamal
  • 5,624
  • 19
  • 34