Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get StringBuilder From user

Tags:

java

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??

like image 343
Cid Avatar asked Feb 15 '23 15:02

Cid


2 Answers

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!

like image 86
John Snow Avatar answered Feb 22 '23 23:02

John Snow


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)

like image 41
ddavison Avatar answered Feb 23 '23 00:02

ddavison