Alright, so I have a driver class and an arraylist (as you can probably guess).
My arraylist is full of strings and I'm accessing it through a getter that I've created in my other class.
It says that "The static method getMouseList() from the type Desktop should be accessed in a static way". How should I go about fixing this? Do you see any other errors?
Thanks to everyone who can help!
So here's my code:
Class:
static ArrayList <String> Strings;
public static void main(String[] args) {
Strings = new ArrayList <String>();
Strings.add("goodbye");
Strings.add("hi");
Strings.add("hello");
}
public static ArrayList<String> getStrings() {
return Strings;
}
Driver class:
Desktop test4 = new Desktop();
System.out.println(test4.getStrings());
Since it's static, it belongs to its class, not to a class instance. Thus, you need to access it using the class: Desktop.getStrings()
UPDATE
I'd need to see more of your code to exactly explain what's going on. So, I'll try to explain on what I imagine is your code. Please note that Java programs start from one main method. Depending on how you execute your program, one of them is going to be invoked, the others will not.
In any case, one way would be to create another static method in Desktop and move the initialization code from main to that method, such as:
public static void initializeStrings(){
Strings = new ArrayList <String>();
Strings.add("goodbye");
Strings.add("hi");
Strings.add("hello");
}
Then, make sure that you call that method, via Desktop.initializeStings(); before trying to access the Strings array (for example in the start of the actual main method of your program.
EDIT 2:
OK, so your main should now look something like this:
public static void main(String[] args) {
Desktop.initializeStrings();
Driver.doSomething();
}
and your Driver's method (inside Driver class):
public static void doSomething() {
//some code
//strings are initialized and will get printed
System.out.println(Desktop.getStrings());
}
That should give you a hint on how to move forward. On a side note, all this staticness is hindering the Object oriented nature of Java. I would suggest a tutorial in Java's object oriented programming model: https://docs.oracle.com/javase/tutorial/java/index.html
Related
I'm trying to create a subclass which auto creates itself. I defined Base which holds a list of instances. Then I defined Derived with a static member reg. reg is in place initialized by calling Base.Register(), which adds it to the instances list.
In the main() I'm printing the instances list of Base. But there is no initialization and I get an error - the instances list is null.
In a further attempt, I added a list of Booleans to Base. Whenever I register an instance, I'm changing this list. I also print this list in the program. I expected it to force the execution of the Base.register(), but to no avail.
I did find a solution that worked, but I don't appreciate - I could print the result of the Base.register() as saved in the Derived. That would force the static initialization. However, I intend to use the solution for a bunch of derived classes, and I wouldn't want to have to call each derived class directly.
Is there a way to force the static init?
I guess I could use reflections, I'm trying to avoid that at the moment.
EDIT what I am actually trying to do, is to build a set of derived classes (for unit testing). All classes derive Base. I want to avoid the need to create instances separately for each. I'm trying to get a generic solution, in each derived class code (only). Such a solution would be easy to copy & paste.
public class StaticTest {
private static class Base{
private static ArrayList<Base> _instances = null;
private static ArrayList<Boolean> _regs = null;
public static int _count = 0;
public static void init(){
_regs = new ArrayList<>();
for (int i=0;i<10;i++)
_regs.add(false);
}
protected static boolean register(Base b)
{
if (_instances == null)
_instances = new ArrayList<>();
_regs.set(_count++, true);
return _instances.add(b);
}
public static void printAll(){
for (Boolean b: _regs)
System.out.printf("hello %s%n", b.toString());
for (Base b: _instances)
System.out.printf("hello %s%n", b.toString());
}
}
private static class Derived extends Base{
public static boolean _reg = Base.register(new Derived());
}
public static void main(String[] args) {
//System.out.print(Derived._reg ? "0" : "1");
Base.init();
System.out.printf("Base._count = %d%n",Base._count);
Base.printAll();
}
}
Short answer is that static initialization occurs only when a class is first used. When you invoke Base.init(), Derived hasn't been yet used and so register hasn't been called.
Medium answer is that if you uncomment the line System.out, you get a NullPointerException because the static code in Derived calls to register before init initializes the Arraylist. Moving the init to the first line solves it and it works as you wanted.
Final answer, if you're trying to understand how a Java classes initializes and it's limitations, it's ok, but the mechanism you're trying to write is a very bad design. Please provide the real problem you're trying to solve and someone can point you in the right direction.
i'm working on a project that i have to use HashMaps on.
I'm fairly new to java, so am i right in thinking that you have to include this in each class that I want to use HashMaps on, or should this be included in each class anyway?
public static void main(String args[])
This is the whole class. Ive tried it without the main method but I just get errors.
import java.util.HashMap;
public class Product
{
public static void main(String args[]) {
HashMap<String, int> product = new HashMap<String, int>();
product.put("product1", 1);
product.put("product2", 2);
}
}
If i dont have the main method in it comes up with an error on the line...
product.put("prodcut1", 1);
It's not that your code has to be in the main method, but it has to be in some method, or an initializer block. If you put your code in a non-main method, it will still work fine.
You only need main in the driver of your program not in every single class. After having written your code/classes that require HashMaps you can then put them inside
public static void main(String args[])
Also since you mentioned HashMaps are not working, have you imported them in the other classes where you are trying to use them like so?
import java.util.HashMap
Short answer: no. A main method serves as the main starting point for an entire program. It has no bearing on what classes can be used in the program.
If you want to use a HashMap...
Include the package that houses the HashMap class
Declare variables of the type HashMap
Either as instance fields of a class or as local variables in a method/function
Use the variables you declared
If you are looking for a way to declare the HashMap at the time of declaration and you dont want the initialization to be in a method or block, you can use the following:
HashMap<String, int> product = new HashMap<String, int>(){{
put("product1", 1);
put("product2", 2);
}};
I don't understand why methods on arrays, in Java, have to be static. Static methods can only be used on static variables right? So this would mean arrays are static variables, variables shared by a class? But what class would this be?
Can someone help me understand this?
Edit: to be more specific, I am creating methods to act on arrays but if I just write "public int[] expandArr(int[]a, int v)" and I try to use this method in the main method, I get an error saying I can't make a static reference to a non-static method. When I write "public static int[] expandArr(int[]a, int v)" it works then.
I understand you cannot change the size of an array, the method I wrote makes a new array with increased size and copies the first one into it.
Thank you.
You say you tried to write this:
public int[] expandArr(int[]a, int v)
The thing is, you had to write it in some class, since you can't just have free-floating methods in your program. Therefore, it must operate on a instance of the class. For example:
public class MyProgram {
public int[] expandArr(int[]a, int v) { ... }
public static void main(String[] args) { ... }
}
expandArr requires an instance of MyProgram, since you didn't declare it to be static. And that has nothing to do with arrays. It would be the same if you wrote
public class MyProgram {
public String expandString(String s, int v) { ... }
public static void main(String[] args) {
String s = expandString(args[0], 1); // ILLEGAL
String s2 = args[0].expandString(1); // ILLEGAL
}
}
Although the first parameter of expandString is a String, this actually operates on a MyProgram, and you cannot use expandString without an instance of MyProgram to operate on. Making it static means that you can (the first use of expandString in my example would become legal.)
In general, you can't add methods to a class without modifying the source of that class. If you want to write a new method that does something with objects of a certain class C, and you can't modify class C (perhaps because it's in the Java library or someone else's library), then you'll need to put the method in some other class C2, and most of the time you will need to make the method static since it doesn't involve objects of class C2.
You can't call a non-static method from a static method unless you first instantiate the an object of the class.
e.g.
In class Whatever...
public boolean ok() {
return true;
}
public static void main(String[] args) {
Whatever w = new Whatever();
System.out.println(w.ok());
}
You cant call a non static method from a static context. A static method belongs to the class, non static or instance methods are copied to each instance of the class (they each have their own). If I have 10 instances of class A, and class A has a static method, which all of them share, then I try to invoke a non static method in class A from class A's static method, which instance of class A gets its method invoked? The behavior is undefined.
The question really has nothing to do with arrays.
This question is related: Can't call non static method
I think what you're referring to is the fact that you can't extend an array class and hence can't add a method to it:
// No way to do this
int[] array;
array.myMethod();
This means your only option is to make a static helper method somewhere:
// So you have to do this
int[] array;
Utils.myMethod(array);
class Utils {
static void myMethod(int[] array) {
...
}
}
An example of this is the Arrays class, which has lots of static methods for operating on arrays. Conceptually it would be clearer if these methods could be added to the array classes, but you can't do that in Java (you can in other languages like Javascript).
That is why we use other classes like the ArrayList to make them grow dynamically in size. At the core of an arraylist you will simply find an array that is renewed in size whenever the class figures out it necessary. If I'm understanding your question right.
Complete beginner here. I am trying to call a method from a class to run in the main class. But I cannot seem to figure out why it is not work. Here is how I am calling the class
public static void main(String[] args) {
findMP3Tracks FT = new findMP3Tracks();
FT.findMP3();
This is the class method i want to call
public static List<String> findMP3(String p)
{
List<String> foundMP3Tracks = new ArrayList<>();
try (DirectoryStream<Path> folderContents = Files.newDirectoryStream(Paths.get(p)))
{
//Look for
for (Path folderItem: folderContents){
if(Files.isDirectory(folderItem, LinkOption.NOFOLLOW_LINKS)) {
foundMP3Tracks.addAll(findMP3(folderItem.toString()));
}
else if(isValidMP3(folderItem.toString())) {
foundMP3Tracks.add(folderItem.toString());
}
}
}
Assuming findMP3(String) is a method inside the class findMP3Tracks (I would recommend you to follow Java conventions for class names), you may call it in the main as:
public static void main(String[] args) {
...
List<String> result = findMP3Tracks.findMP3("Name of MP3");
}
You may use the name of the class findMP3Tracks to invoke the method findMP3, because it is declared as static. So it's not necessary to create an instance to call it. (Of course you may want to create instances of that class for other operations)
Also, since findMP3 is returning a List<String>, you may want to store it in a variable (In the example result)
First, you don't need instances to call a static method, so this line
findMP3Tracks FT = new findMP3Tracks();
is useless, you can remove it.
Use (for example)
findMP3Tracks.findMP3("Some MP3 name");
Also you need to get the returned value, so it should be:
final List<String> mp3List = findMP3Tracks.findMP3("Some MP3 name");
PS: in Java by convention class names start with uppercase, I suggest you change findMP3Tracks class name to FindMP3Tracks
You've declared the method as
public static List<String> findMP3(String p)
which means (among other things) that when you call it, you're going to pass in a String argument. But you wrote
FT.findMP3();
where you're not passing in any argument at all. Something like
FT.findMP3("Hello");
would compile; or if you had a String variable whose value was the name of the MP3 that you wanted to search for, you could use that too. But the call to any method MUST match the declaration of that method.
The method findMP3 is declared as static. Static variables and methods are members of the class.
You can invoke it directly using the classname. So, it should be findMP3Tracks.findMP3()
Also, a word about the static method. If you do know that the behaviour of the method isnt different for different instances, then you might/can declare it as static. Although, it is a design decision that you would make. If it does behave differently based on the passed in parameter, it is better off to have a method which isnt static.
I was around Wikipedia reading about a programming language called 'D', it is the first time I read about it.
It was curious to me that the syntax looks very similar to Java.
But most interesting was when I saw their main method uses char[][].
I opened up Eclipse and I tried this:
public static void main(char [][] args){
}
I was surprised when I saw it compiled with no syntax errors, but I did not understand why.
Can someone explain to me why this call to the main method can compile in Java?
As what you have written is valid Java syntax (static void method with name main and as argument a two dimensional char array) it will compile. The problem however is, that this main method will not work as entry point to a Java program, as this has to have the signature:public static void main(String[] args).
dcn, is correct it is a valid method named main. But can't be used to start a Java app.
To expand further, there is some flexibility in the signature:
You can use any variable name, not just args:
public static void main(String[] whateverNameYouWant) {
}
The variable must be an array of Strings, but you can declare that in any valid Java syntax, like so:
public static void main(String args[]) {
}
As, Michael Krussel, points out, you can also use varargs:
public static void main(String... args) {
}