The Main
Issue:
Can anyone please explain me why is this IDE is saying to create a constructor
for using nextLine()
function?
package Practice.String_9;
import java.util.*;
public class StringBuilder {
public static void main(String[] args) {
Scanner Sc = new Scanner(System.in);
String str = Sc.nextLine();
System.out.println("Entered String is :: " + str);
StringBuilder StrBui = new StringBuilder(Sc.nextLine());
/* I am Getting Error in Above Line And Compiler is Suggesting to either Create a Constructor or remove the `Sc.nextLine()` from `StringBuilder` */
System.out.println("Entered String in StringBuilder is : " + StrBui);
}
}
Output
For The Above Code:
Please explain to me how to get input from using directly in StringBuilder
.
I want to get input inside StringBuilder
from the user.
The problem is that you named your own class StringBuilder
and so you are "shadowing" the class java.lang.StringBuilder
. You can either rename your own class or you reference to java.lang.StringBuilder
with the full package name like this:
package practice.string9;
import java.util.*;
public class StringBuilder {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String str = sc.nextLine();
System.out.println("Entered String is :: " + str);
java.lang.StringBuilder stringBuilder = new java.lang.StringBuilder(sc.nextLine());
System.out.println("Entered String in StringBuilder is : " + stringBuilder);
}
}
As you see that variant is quite bulky to read, so I would recommend to just rename your own class.
The IDE recommends to create a constructor, because your own class does not provide a constructor with a String
parameter, as you call it in the problematic line. I can't figure out, what it wants to tell you about the "redundant" arguments, maybe that you could use the default constructor because it doesn't need arguments and so if you remove the argument to the constructor, the code also would compile.
The output you showed in the screenshot is probably from such an attempt, because it shows a typical output from the default implementation of the toString()
method on your own class that is called by the string concatenation operator +
.