All Leetcode questions don't seem to have main methods, I wonder how I could run the code in a local IDE(say, eclipse)? For instance, I was trying to run this one:
Q: Write a method/function to replace all the space in String s to "%20".
The code:
public class ReplaceSpace {
public String replaceSpace(String s) {
StringBuilder res = new StringBuilder();
for(Character c : s.toCharArray()) {
if(c == ' ')
res.append("%20");
else
res.append(c);
}
return res.toString();
}// that'll work in the Leetcode editor
public static void main(String[] args) {
String s = "We are happy.";
System.out.print(s.replaceSpace); //reports "cannot be resolved to a type" error
}
}
Also, if anyone could explain a little why Leetcode editor could run code without the main method it would be great.
To test the code in your local IDE, simply provide your own main. The pre-written code usually contains non-static methods. This gives you two ways to test your code.
Add static
public class ReplaceSpace
{
public static String replaceSpace(String s)
{
...
}
public static void main(String[] args)
{
System.out.println (replaceSpace("We are happy"));
}
}
Create object
public class ReplaceSpace
{
public String replaceSpace(String s)
{
...
}
public static void main(String[] args)
{
ReplaceSpace rs = new ReplaceSpace();
System.out.println (rs.replaceSpace("We are happy"));
}
}
replaceSpace is a method of ReplaceSpace class and not String class. String is the return type for replaceSpace method. You're trying to call the replaceSpace method on the String class object.
In order to run the code, you need to instantiate an object of ReplaceSpace class and then call the replaceSpace method on its object by passing the string which you want to replace as a parameter. Like so:
public static void main(String[] args) {
ReplaceSpace rs = new ReplaceSpace();
String replacedString = rs.replaceSpace("We are happy.");
System.out.println(replacedString);
}
Another way is to make the replaceSpace method static and call the method without an object instantiation.
As to how Leetcode runs the code behind the scenes, they don't need to use main methods to run your code. They just have unit tests written for your function with exhaustive test cases to test your solution rather than running your code via main methods.
Related
I have the following global variable of String type.
static public String rev="hello"
I can read it without any issue from an object of another class. Is there anyway I can update it with another string from an object of another class? I know Java string is immutable. I tried with the following way using StringBuilder:
static public StringBuilder rev=new StringBuilder("hello");
static public void setRev(StringBuilder s)
{
rev=rev.delete(0,rev.length());
rev.append(s);
}
From another class:
MainActivity.setRev(stringBuilderVar);
But it did not work.
The syntax for updating a field is the same for static and non-static fields. Simply use an assignment statement:
class Global {
public static String greeting;
}
public class Other {
public static void main(String[] args) {
String newGreeting = "hello";
Global.greeting = newGreeting;
}
}
That said, once your programs get bigger, you'll likely want to use non-static fields instead.
public class CodingBat {
public static void main(String[] args) {
System.out.println(sumDouble(5,5));
}
public int sumDouble(int a, int b) {
if( a ==b) {
return 2*a + 2* b;
} else{
return a + b;
}
}
}
So I made this code, and I'm really confused why it doesn't work unless I write static between the public int sumDouble, because I was practicing on codingBat, and to answer the question they did not involve static, but then how do they test code. Do they use the main? I mean you have to to get the code running right?
So to my knowledge, static means that every object of this class will all contain the same value.But I don't see the relevance of this error.
"Cannot make a static reference to the non-static method"
Thank you for your help :D
and I'm really confused why it doesn't work unless I write static
between the public int sumDouble,
Yes, static is required
Since the main method is static and the sumDouble() method is not, you can't call the method without creating object of class. You cannot refer non-static members from a static method.
Either make method static or create object as below and then access method.
CodingBat obj = new CodingBat();
System.out.println(obj.sumDouble(5,5));
Refer here for more
Either you call it through a static context, meaning like you do (or, from another class, by: ClassName.methodName(); )
Or, you have to call it as an instance method, which it is, if you don't declare it static.Then, however, you'll need an instance to call it through:
public static void main(String[] args){
CodingBat cB = new CodingBat();
System.out.println(cB.sumDouble(5,5));
}
You need to create an object in order to use this method
public class CodingBat {
public static void main(String[] args){
CodingBat obj = new CodingBat();
System.out.println(obj.sumDouble(5,5));
}
public int sumDouble(int a, int b) {
if( a ==b){
return 2*a + 2* b;}
else{
return a + b;}
}
}
I forgot a concept that I used and can't remember it.
For the context, I used to have a method like toString() which had a parameter. This parameters allowed me to call my method like myMethod(System.out::println) to print it on the screen, but also to print it in a file with the same syntax.
Does anyone know what can be this parameter? the concept?
I think it's kind of a FunctionalInterface but I don't know what it is.
This is called method reference and applies when you know what method you want to call, provided the method already exist.
From the tutorial :
Because this lambda expression invokes an existing method, you can use
a method reference instead of a lambda expression:
Arrays.sort(rosterAsArray, Person::compareByAge);
Available since Java-8.
An exemple using what you want:
public static void function(String s, Consumer<String> f) {
f.accept(s);
}
public static void main(String args[]) {
String test1 = "test";
String test2 = "test2";
function(test1, System.out::println);
function(test2, System.out::println);
function(test1, System.out::print);
function(test2, System.out::print);
}
This goes well with java 8 functional interface:
#FunctionalInterface
static interface MyPrinter {
public void println(String line);
}
static void myMethod(MyPrinter mp) {
mp.println("Hello wolrd");
}
...
public static void main(String[] args) throws IOException {
myMethod(System.out::println);
PrintWriter pw = new PrintWriter("myFile.txt");
myMethod(pw::println);
pw.close(); //never forget to close file output streams!
//EDIT: note that you can of course store your MyPrinter in a variable:
MyPrinter mp = System.err::println;
myMethod(mp);
}
Would this work for you?
public class C {
static void myMethod(java.io.PrintStream p) {
p.println("Hello!");
}
public static void main(String args[]) {
myMethod(System.out);
}
}
Unfortunately you can't pass System.out.println directly, because in Java methods (before Java 8) are not first-class objects. All you can do with a method is calling it. As a workaround, you can introduce an interface and create an adapter class.
In java, I have two classes in two separate files, and I'm trying to get my print method to work in the second class.
The print method is a non-static (it has to be non-static, no choice)
this is some of the print code:
public void print() {
System.out.print(re);
if (im < 0) {
System.out.print("something");
}
else if (im > 0) {
System.out.print("something else");
}
System.out.println("");
return;
}
And every time I try to print in the second class, I find that non-static method print() cannot be referenced from a static context.
How do I get this to print in the new class?
You create an instance of the class with the non-static method.
MyClass myObject = new MyClass();
myObject.print();
In almost every java application, I tend to write a default main method to break out of the static one. Here's an example of how I accomplish it. Maybe this will help you when writing future applications.
public class Foo {
public int run (String[] args) {
// your application should start here
return 0; // return higher number if error occurred
}
public static void main (String[] args) {
Foo app = new Foo();
int code = app.run (args);
System.exit (code);
}
}
I have a simple problem that I've been stuck on for some time and I can't quite find the answer to. Basically, I'm creating an object and trying to access the variables without using static variables as I was told that is the wrong way to do it. Here is some example code of the problem. I receive an error in the first class that can not be resolved to a variable. What I would like to be able to do is access t.name in other methods outside of the main, but also in other classes as well. To get around this previously I would use Test2.name and make the variable static in the Test2 class, and correct me if I'm wrong but I believe that's the wrong way to do it. Any help would be greatly appreciated =)
public class Test {
public static void main(String[] args) {
Test2 t = new Test2("Joe");
}
public void displayName() {
System.out.println("Name2: " + t.name);
}
}
public class Test2 {
String name;
public Test2 (String nm) {
name = nm;
}
}
I see others have posted code snippets, but they haven't actually posted why any of this works (at the time of this writing.)
The reason you are getting a compilation error, is that in your method
public static void main(String[] args) {
Test2 t = new Test2("Joe");
}
Variable t's scope is just that method. You are defining Test2 t to only be in the main(String[] args) method, so you can only use the variable t in that method. However, if you were to make the variable a field, like so, and create a new instance of the Test class,
public class Test {
Test2 t;
public static void main(String[] args) {
Test test = new Test();
test.t = new Test2("Joe");
test.displayName();
}
public void displayName() {
System.out.println("Name2: " + t.name);
}
}
Then you should no longer be getting any compilation errors, since you are declaring the variable t to be in the class Test scope.
You may give the reference to your test object as an argument to method displayName:
public class Test {
public static void main(String[] args) {
Test2 t = new Test2("Joe");
displayName(t);
}
public static void displayName(Test2 test) {
System.out.println("Name2: " + test.name);
}
}
Note: I also made displayName a static method. From within your main method you can only access static methods without reference.
Modify the Test class to this
public class Test {
private static Test2 t;
public static void main(String[] args) {
t = new Test2("Joe");
}
public void displayName() {
System.out.println("Name2: " + t.name);
}
}
Use a getter for your purpose. This is a side solution to your problem, but generally this is how you should retrieve instance variables, using getters.
public class Test {
public static void main(String[] args) {
Test2 t = new Test2("Joe");
displayName(t);
}
public static void displayName(Test2 test) {
System.out.println(test.getName());
}
}
public class Test2
{
private String name;
public Test2 (String nm)
{
name = nm;
}
public String getName()
{
return name;
}
}
Always remember, variables in your class should be private. That protects it from access from outside the class. Hence, getters are the only way to access them. And setters or constructors to initialize them.
Fewer statics the better I reckon.
I would Instantiate Test and call displayName on the instance of it, then pass the instance of Test2 to displayName.
But it does depend on what the overall aim is