import java.util.*;
import java.io.*;
public class LootGenerator{
public static void main (String[] args)
throws FileNotFoundException{
System.out.println("This program simulates the random item generator");
System.out.println("from the game Diablo II. Happy hunting!");
System.out.println();
String file="monstats.txt";
Monster[] array = getArray(file);
//Monster alex=getRandomMonster(array);
}
public Monster getRandomMonster(Monster[] array){
int randMonster = (int)(Math.random() * array.length);
return array[randMonster];
}
public Monster[] getArray (String file)
throws FileNotFoundException{
Scanner sc = new Scanner (new File (file));
Monster[] array = new Monster[sc.nextInt()];
sc.next(); //takes away the word Class
sc.next(); //takes away the word Type
sc.next(); //takes away the word Level
sc.next(); //takes away the word TreasureClass
for(int a = 0; a < array.length; a++)
{
array[a] = new Monster(sc.next(), sc.next(), sc.nextInt(), sc.next());
}
return array;
}
}
class Monster{
private String monsterClass;
private String type;
private int level;
private String treasureClass;
public Monster(String myClass, String myType, int myLevel, String myTreasureClass){
monsterClass = myClass;
type = myType;
level = myLevel;
treasureClass = myTreasureClass;
}
public String getMonsterClass(){
return monsterClass;
}
public String getType(){
return type;
}
public int getLevel(){
return level;
}
public String getTreasureClass(){
return treasureClass;
}
}
I can’t figure out what is wrong with my program…any advice? I keep getting that it can’t be referenced from a static context – the line Monster[] array = getArray(file) that is. The object of the program is to randomly generate a monster from a text file – the assignment is here if you need to look at the text file itself: http://www.cis.upenn.edu/~cis110/hw/hw06/index.html
You’re trying to call a regular method from a static method, which isn’t possible. You could instantiate LootGenerator and then call the method or make the method static (simply add the static modifier to the method).
One solution:
You can find more information about instance and class members here.
In short, instance methods can only be called on instances of a class. Static methods belong to the class and can be called from anywhere, but they can’t access instance variables or call instance methods unless they actually have a reference to an instance of a class.