This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Static method in java
Ok, so I'm working on a project for a class I'm taking.. simple music library. Now I'm having some issues, the main issue is I'm getting "non-static method cannot be referenced from a static context"
Here is a function I have
public void addSong() {
Scanner scan = new Scanner(System.in);
Song temp = new Song();
int index = countFileLines(Main.databaseFile);
index = index + 2;
temp.index = index;
System.out.print("Enter the artist name: ");
temp.artist.append(scan.next());
}
Now thats in a class file called LibraryFunctions. So I can access it with LibraryFunctions.addSong();
Now I'm trying to run this in my main java file and its giving me the error, I know why the error is happening, but what do I do about it? If I make addSong() a static function then it throws errors at me with the Song temp = new Song() being static. Kind of ironic.
Much help is appreciated on this!
Follow these simple rules:
If it's a static method call it with ClassName.methodName()
If it's a non-static method call it with classInstance.methodName()
If you want to call it as LibraryFunctions.addSong(), it needs to have the signature public static void addSong().
More info:
Only static methods can be called without instantiating a class first.
You can also try:
LibraryFunctions lf = new LibraryFunctions();
lf.addSong();
Well you have two options really:
Change addSong() to static and reference Song through it's static members if possible.
Create a new instance of LibraryFunctions and then use the non-static method addSong()
I take that your class Song is a non static nested class? e.g.
class LibraryFunctions {
class Song {
// ...
}
}
If so you can either make it a static nested class, or lift the Song class into a separate class.
In terms of structure, may I suggest that the LibraryFunctions class file be turned into a MusicLibrary class? That way, in your main application code, you can instantiate a MusicLibrary every time the code runs. It will also make it easier to separate static functions and instance functions, which would probably solve your issue right now.
public class MusicManager {
public static void main(String[] args) {
MusicLibrary myMusic = new MusicLibrary();
myMusic.addSong();
// other stuff
}
}
Then MusicLibrary:
public class MusicLibrary {
public MusicLibrary() {
}
public void addSong() {
Scanner scan = new Scanner(System.in);
Song temp = new Song();
int index = countFileLines(Main.databaseFile);
index = index + 2;
temp.index = index;
System.out.print("Enter the artist name: ");
temp.artist.append(scan.next());
}
}
And finally, I would put the class Song outside of MusicLibrary so that you can reuse it later.
Another added benefit of this is that you can make MusicLibrary implement Serializable and save the library to a file. Plus you could place an array of MusicLibraries inside of a MusicLibrary and have playlists. All kinds of options.
Related
I've run into a problem where I attempt to define a constructor in the first part of a switch/case statement, and then I can't run the code because the program can't get the definition later.
The idea behind passing the constructor information from a switch/case function is that the user chooses what to do, but for some options, one must be done before the other is possible (e.g. Create password and Check password).
If I try doing it this way, it throws a VarMayNotHaveBeenInitialized error (I get the sense the answer is in a try/catch statement, but I don't know enough about them to be sure). I've included some code that is what I've been essentially trying to do below. (The two classes are to best simulate the project I'm working on.)
Any help is appreciated! : )
TestMain.java:
package exitTest;
public class TestMain {
InitializeTest init;
public static void main(String[] args) {
while (true) {
String x = InitializeTest.askQuestion();
switch (x) {
case "set":
InitializeTest init = new InitializeTest();
break;
case "get":
if (init != null) {
init.showExample();
} else {
System.out.println("Error: init not initialized.");
} break;
}
}
}
}
InitializeTest.java:
package exitTest;
import java.util.Scanner;
public class InitializeTest {
static Scanner in = new Scanner(System.in);
public InitializeTest thing1;
public String example;
public static String askQuestion() {
System.out.println("set for set example\nget for check example");
String action = in.nextLine();
return action;
}
public InitializeTest() {
System.out.println("Input string:");
String example = in.nextLine();
}
void showExample() { System.out.println(example); }
}
You include the type when you're declaring variables, not when simply assigning to an existing one. When you write
InitializeTest init = new InitializeTest();
That makes a new init variable, unrelated to the previous one, which stores the newly constructed object. That new variable shadows the existing one, but it gets released after the switch block is over (variables in Java are block-scoped).
To put it to an analogy, it's as though you wanted to tell your friend Alice a secret. But when you went to her house, her neighbor whose name is also Alice happened to be there instead. If you tell that Alice your secret, then your friend doesn't find out. Even though the two happen to share a name, they don't share any memory.
I am trying to print the number increment by 1 whenever i call the function, but i am not able to get the solution, below is my code
The blow is the function
public class Functions<var> {
int i=0;
public int value()
{
i++;
return i;
}
}
I am calling the above function here
import Java.Functions;
public class Increment {
public static void main(String[] args)
{
Functions EF = new Functions();
System.out.println(EF.value());
}
}
Whenever i run the program , i am getting only the output as 1 , but i want the output to be incremented by 1 . Could you please help. Thanks in Advance.
I believe your answer is with the scope of your variables and your understanding of them. You only call the method once in your given examples, so 1 is arguably the correct answer anyway. Below is a working example which will persist during runtime one variable and increment it every time a function is called. Your methods don't seem to follow the common Java patterns, so I'd recommend looking up some small example Hello, World snippets.
public class Example{
int persistedValue = 0; // Defined outside the scope of the method
public int increment(){
persistedValue++; // Increment the value by 1
return persistedValue; // Return the value of which you currently hold
// return persistedValue++;
}
}
This is due to the scope of "persistedValue". It exists within the class "Example" and so long as you hold that instance of "Example", it will hold a true value to your incremented value.
Test bases as follows:
public class TestBases {
static Example e; // Define the custom made class "Example"
public static void main(String[] args) {
e = new Example(); // Initialize "Example" with an instance of said class
System.out.println(e.increment()); // 1
System.out.println(e.increment()); // 2
System.out.println(e.increment()); // 3
}
}
If your desire is out of runtime persistence (the value persisting between application runs) then it would be best to investigate some method of file system saving (especially if this is for your Java practice!)
Your main problem is to increment the number value 1.
But you are calling your function only once. Even though you call the function many times you will get the value 1 only because it is not static variable so it will every time initialize to 0.
So please check below answer using static context.
Functions.java
public class Functions{
static int i=0;
public int value()
{
i++;
return i;
}
}
Increment.java
public class Increment{
public static void main(String []args){
Functions EF = new Functions();
System.out.println(EF.value());
System.out.println(EF.value());
System.out.println(EF.value());
}
}
Output:
1
2
3
If you design multi-threaded application, it will be better to use AtomicInteger.
The AtomicInteger class provides you an int variable which can be read and written atomically.
AtomicInteger atomicInteger = new AtomicInteger();
atomicInteger.incrementAndGet();
im quite a beginner in Java and im facing a problem with my code.Bascially I have a class containing a method that create a listarray based on user input:
public class manage{
public void adding() {
boolean loop = true;
ArrayList<Game> thegame = new ArrayList<Game>();
while(loop) {
Scanner agame = new Scanner(System.in);
System.out.print("name: \n");
String Cgame = agame.nextLine();
Scanner qty = new Scanner(System.in);
System.out.print("the qty: \n");
int CQty = qty.nextInt();
Console wertgame = new Console(Cgame,Cqty);
thegame.add(new Game(Cgame,Cqty));
System.out.println("continue?");
Scanner autre = new Scanner(System.in);
int continu = other.nextInt();
if(continu==1) {
}
else if(continu==2) {
Main.menu();
}
}
return thegame;
}
And then I have another method in the same class that is to display it:
public void information(List<Game> thegame) {
System.out.print(thegame);
}}
The problem im having here, is that I need to access the information(List thegame) method, from another class(java file).However,how do I access it from my other class since I cant access(call) it using "manage.information()"since it needs argument,but my arraylist isnt created yet in my other class,it gets create only when in the manage class.So I cant pass the arguments when calling it.How do I access/call it from my other class then?
thank you
The simple answer is that you can't.
If you want to call a method that requires an argument, then you need to pass that argument in some form or another.
IMO, the best solution would simply be to not call the information method at the point where you don't have the argument it requires. The sole purpose of the method seems to be to print out its argument, so if you don't have an object (list) to print then the method call cannot do anything worthwhile.
Alternatively, you could pass a null instead of a list, but that will simply result in the method outputting "null" which seems rather pointless.
In short, you can't pass an argument that doesn't exist. It simply makes no sense. Think again about what you are actually trying to do here.
I have try many things, and I am so stuck in this problem.
I have to read from a text file, and throw it inside an arraylist in a private method.
And then make a new method that will print the arraylist out.
This is what I have tried so far.
I get this error:
fileHandling.java:11: readArray(java.util.ArrayList<java.lang.String>) in fileHandling cannot be applied to ()
readArray();
^
1 error
My code:
import java.util.Scanner;
import java.io.*;
import java.util.*;
public class fileHandling {
private ArrayList<String> Person;
public static void main(String[] args)throws Exception {
readArray();
}
private ArrayList readFile() throws Exception {
File file = new File("person.rtf");
Scanner scanner = new Scanner(file);
while(scanner.hasNextLine()) {
String str = scanner.nextLine();
Person.add(str);
}
return Person;
}
public void readArray(ArrayList<String> Person) {
for(int i =0; i < Person.size(); i++) {
System.out.println(Person.get(i));
}
}
}
I think the error is when I called my method, what is going inside the brackets?
You have a few issues (that I see).
1) You aren't instantiating an instance of your class.
2) You aren't reading the file.
3) You aren't calling readArray with the List.
4) You have no List instance.
5) ArrayList<String> readFile()
I think you want something like this,
private ArrayList<String> Person = new ArrayList<String>();
public static void main(String[] args) throws Exception
{
// readArray();
fileHandling fh = new fileHandling();
fh.readArray(fh.readFile()); // <-- something like this
}
You should use a bufferedInputStream to read your file...
variables should not be capitalized and your array should also be called persons and not Person.
Don't forget to initialize your
ArrayList persons = new ArrayList();
Your main method should call the read method first.
If you use Java 7, it is as easy as:
// returns a List<String> with all lines in the file
Files.readAllLines(thePath, StandardCharsets.UTF_8);
First you won't be able to access readArray() from your main since readArray() is not static. In your current context you'd need to create an instance of fileHandling in your main and call readArray() on it.
Second, your readArray() method is declared with an ArrayList Person as a parameter, but you're calling it without the parameter in your main method.
Third, it won't help with the compilation, but rule of thumb in Java is to capitalize the first letter of a class (Should be FileHandling) and to not capitalize the first letter of a declaration (ArrayList Person should really be ArrayList person).
In this book, there is this example of how to use static variables and methods. I dont understand what is going on. explain why there has to be static in front of the methods and variables. There are two seperate classes called Virus and VirusLab. The VirusLab.java takes in a command line argument and makes the amount of Virus objects, then spits out the number of Virus objects. Thanks
Virus:
public class Virus {
static int virusCount = 0;
public Virus() {
virusCount++;
}
public static int getVirusCount() {
return virusCount;
}
}
VirusLab:
public class VirusLab {
public static void main(String[] args) {
int numViruses = Integer.parseInt(args[0]);
if (numViruses > 0) {
Virus[] virii = new Virus[numViruses];
for (int i = 0; i < numViruses; i++) {
virii[i] = new Virus();
}
System.out.println("There are " + Virus.getVirusCount()
+ " viruses.");
}
}
}
A web search would have given you hundreds of links to explain 'static' keyword in Java.
Please refer to the following documentation: http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html
Also, please refer a text book for your further learning, that will help a lot.
I will keep it pretty short
You need static variables if you want that variable to be shared
across all the objects of your class,so that if one of the object
changes its value it would be reflected in other objects as well,which
is what is exactly done in above example.
A static variable is one which is not associated with an instance of a class.
This means you don't have to create a new instance of the class to access the variable from another class. Consider this:
public class Login {
public static String loggedInUser
public void setLoggedInUser(String name){
this.loggedInUser = name;
}
}
To access the String loggedInUser in another class, you wouldn't have to say
Login login = new Login();
String username = login.loggedInUser;
You'd just have to say
String username = Login.loggedInUser;
This can be useful in accessing variables outside of the class they were set in.
Hope that helps.
try reading this answer I gave in a previous question:
Accessing Static variables
and make google and wikipedia ur friend they'll save u time coming on here posting questions ,waiting and refreshing ur page to check if any answers were given.