I want to print my name's letters one by one like so:
Result:
A
Af
Afs
afsh
afsha
afshan
.....
I've tried this coding but its a simple loop and it showing my complete name.
char[]aar={'a','f','s','h','a','n'};
for(int b=0; b<1;b++){
String str=new String(aar);
System.out.println(""+str);
}
It sounds like you want to print a substring of your name on each step. So start with the complete name:
String name = "Afshan";
and then loop for as many letters as there are (using String.length()
to check) and then print the substring from the start to that iteration number - use name.substring(0, i + 1)
to get the relevant substring where i
is the variable in the loop. Read the documentation for substring
carefully to see what each of the parameters means (and why you want i + 1
rather than i
).
It's important to use i
in the body of the loop, otherwise you will be printing the same thing on each iteration.
I won't provide the full code here, as you're trying to learn (yay) but as an aside, try to avoid using "" + ...
- in your existing code, you don't need it anyway, as str
is already a string, but if you do need to convert a different type into a string, use String.valueOf(x)
instead. That says exactly what you want to do, whereas concatenation with an empty string doesn't.
See more on this question at Stackoverflow