how can i get StringBuilder
from users through Scanner
class??
or any other classes?
i know that we can get a string and then put it in a StringBuilder
like this:
import java.util.Scanner;
public class Sade {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String str;
str = scan.nextLine();
StringBuilder strb = new StringBuilder(str);
}
}
or through using append()
.
but is there anyway to get StringBuilder
directly from user??
You misunderstand the StringBuilder Class.The principal operations of a StringBuilder are the append and insert methods, which are overloaded so as to accept data of any type. Each effectively converts a given datum to a string and then appends or inserts the characters of that string to the string builder. The append method always adds these characters at the end of the builder; the insert method adds the characters at a specified point. The best thing you can do with your code is :-
import java.util.Scanner;
public class sb {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
StringBuilder strb = new StringBuilder(scan.nextLine());
strb.append( scan.nextLine());
System.out.println(strb);
}
}
Ofcourse,it is the same as you posted!
You cannot fetch a StringBuilder
object from the Standard Input, but you can output to the user enter the strings (type 'exit' to exit):
and formulate your own.
Loop through this until they type 'exit', and each time you fetch the string, you can do myStringBuilder.add(theirInput)
(this, of course, is pseudo-code)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With