2013-08-13 3 views
0

Я кодирую маленькую игру для своего развлечения, и у меня возникла проблема с получением переменной, которую нужно изменить в одном классе из значения в другом. Я действительно сделал это в другом классе, который не был основным. Ошибка, которую я получаю при запуске, заключается в том, что мне нужно main() быть main(String[] args), который я изменил на main(int wgold).Как изменить значение переменной в основном классе из другого класса?

import java.io.*; 


class player { 
    public static void main (String[] args) throws IOException { // <<<<<<<<<<<<<<<<<<<<< Need to have this get the value sent 
     String Name, cmd; 
     int gold, quit, spaces, weint, randGold; 

     gold = 0; 
     cmd = "none"; 
     quit = 0; 
     spaces = 0; 
     weint = 0; 

     /* Ideas for new commands: 
     attack - Attacks monster you have run into. - 100% 
     eat - Heals you. - 0% 
     run - Gets you away from a battle. - 100% 
     walk - Moves you one space and you can: find something (gold, food, ect...) or run into a monster. - 50% 
     */ 

     while (quit == 0) { 
      gold += wgold; // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< This is the setting of the gold after the battle >>>>>>>>>>>>>>>>>>>>>>> 
      wgold = 0; 
      if (cmd.equalsIgnoreCase("none")) { 
       System.out.println("-------Commands-------\n"); 
       System.out.println("distance - Displays the amount of spaces you have walked."); 
       System.out.println("gold - Shows the amount of gold you have."); 
       System.out.println("quit - Exits the program."); 
       System.out.println("walk - Moves you one space.\n"); 
       System.out.println("--End of command list--\n"); 
       cmd = "wait"; 
       BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in)); 
       System.out.print("Command: "); 
       System.out.flush(); 
       cmd = stdin.readLine(); 
      } 

      if (cmd.equalsIgnoreCase("gold")) { 
       System.out.println("\nGold: " + gold + "\n"); 
       cmd = "none"; 
      }else if (cmd.equalsIgnoreCase("walk")) { 
       spaces += 1; 
       weint = misc.random(1000); // Sets a random number out of 1000 for a percentage. 
       if ((weint >= 0) & (weint < 300)) { 
        enemies obj = new enemies(); 
        obj.main(); 
        cmd = "none"; 
       } else if ((weint >= 300) & (weint < 500)) { 
        randGold = misc.random(10); // Sets the random amount of gold found while walking. 
        if (randGold <= 0) { 
         randGold = 1; 
        } 
        System.out.println("\nYou have walked one space and found " + randGold + " gold piece(s).\n"); 
        gold += randGold; 
        cmd = "none"; 
       } else if ((weint >= 500) & (weint <= 1000)) { 
        System.out.println("\nYou have walked one space.\n"); 
        cmd = "none"; 
       } 
      } else if (cmd.equalsIgnoreCase("distance")) { 
       System.out.println("\nSpaces you have moved: " + spaces + ".\n"); 
       cmd = "none"; 
      } else if (cmd.equalsIgnoreCase("quit")) { 
      System.out.println("Quitting the program..."); 
      quit = 1; 
      } else { 
       System.out.println("\nCommand not recognized.\n"); 
       cmd = "none"; 
      } 
     } 
    } 
} 

class battle { 
    public static void main(String monster, int level, int mhp, int drop) throws IOException { // (String monster) gets the return value of the monster sent by the enemies class. 
     int end, hp, str, smhp, exp; 
     Long hit; 
     String cmd; 

     end = 0; 
     hp = 10; 
     str = 1; 
     exp = 0; 
     smhp = mhp; 
     cmd = "none"; 

     System.out.println("\n\n\n-------Battle!-------\n\n\n"); 
     System.out.println("You've encountered a wild " + monster + " level " + level + "!\n\n"); 

     while(end == 0) { 
      if(cmd.equalsIgnoreCase("none")) { 
       System.out.println("----Commands----\n"); 
       System.out.println("attack - Attacks the enemy."); 
       System.out.println("run - Runs from battle.\n"); 
       System.out.println("--End of command list--\n\n\n"); 
       System.out.println("-----Status----\n"); 
       System.out.println("HP: " + hp + "/10"); 
       System.out.println("Strength: " + str + "\n"); 
       System.out.println("---Wild " + monster + " stats---"); 
       System.out.println("Wild " + monster + " HP: " + mhp + "/" + smhp + "\n"); 
       cmd = "wait"; 

       BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); 
       System.out.print("Command: "); 
       System.out.flush(); 
       cmd = stdin.readLine(); 
      } 

      if(cmd.equalsIgnoreCase("run")) { 
       System.out.println("\nYou have escaped from the battle!\n"); 
       end = 1; 
      } else if(cmd.equalsIgnoreCase("attack")) { 
       hit = Math.round(misc.random(str) * .7); 

       System.out.println("You hit: " + hit); 
       mhp -= hit; 

       if(hit >= 1) { 
        exp += hit * 12; 
       } 

       cmd = "none"; 
       //Add HP for monsters/attack command. Not all here but you know where... 
      } else { 
       System.out.println("\nCommand not recognized.\n"); 
       cmd = "none"; 
      } 

     if(mhp <= 0) { 
      System.out.println("You have won!"); 
      System.out.println("You found: " + drop + " coins!"); 

      player obj = new player(); // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< This is where the value is sent to the player class 
      obj.main(drop); 

      if(exp >= str * 80) { 
       str += 1; 
       System.out.println("Congradulations! You now have " + str + " strength."); 
      } 
      end = 1; 
     } 

     } 
    } 
} 

class enemies { 
    public static void main() throws IOException { 
     String monster; 
     int drop, level, mint, mhp; 

     mint = misc.random(10); 

     if (mint >= 7) { 
      monster = "Goblin"; 
     } else { 
      monster = "Wizard"; 
     } 

     battle obj = new battle(); // calls the battle class 

     level = misc.random(3); // Makes a random level for the enemy. 

     mhp = level + 3; 

     drop = misc.random(level); 

     if(drop <= 0) { 
      drop = 1; 
     } 

     drop = drop * 3; 

     obj.main(monster, level, mhp, drop); // sends the String monster to the battle class. 
    } 
} 

Я знаю, что мой код является беспорядок и есть, вероятно, много вещей, которые я мог бы сделать по-другому, но я только учусь в данный момент. Любая помощь будет очень оценена.

Этот код также доступен здесь: http://pastebin.com/kjuD3GJd

ответ

3

Вам нужна ссылка на экземпляр основного класса. Что-то по следующей коде Эскиза (будет содержать опечатки)

public class Main{ 
    public static void main (String[] args){ 
     new Main().start(); 
    } 
    public void start(){ 
     new OtherClass(this).doSomething(); 
    } 

    public void whatever(){...} 
} 

public class OtherClass{ 
    private final Main main; 
    public OtherClass(Main aMain){ 
     main = aMain; 
    } 
    public void doSomething{ 
     main.whatever(); 
    } 
} 

Внутри метода whatever вы можете получить доступ ко всему состоянию экземпляра Main. Конечно, вы также можете передавать параметры.

Что касается другого вопроса неявный вопрос: для запуска программы вы должны использовать метод static void main(String[] args). Все остальное не будет работать. Конечно, вы можете использовать произвольные другие методы, включая некоторые с тем же именем, хотя я бы рекомендовал использовать уникальные имена для начинающих. Это позволяет избежать компилятора, запутывающего вас о том, какой метод он жалуется.

В качестве дополнения некоторые советы по заданию вопросов здесь: Скопируйте (*) ваш код в новый проект. Затем удалите все, что вам не нужно, чтобы понять вашу проблему. В 9 из 10 случаев вы найдете решение своей проблемы в процессе. В последнем случае у вас есть образец кода, на который люди фактически смотрят, в результате чего получаются гораздо лучшие ответы.

(*) вместо копирования системы управления версиями, например. рекомендуется, но я думаю, вы еще не там.

+0

Я получаю в основном то, что это делает, и должен ли я делать их в подклассах вместо каждого другого класса, или я делаю это правильно? Я все еще немного смущен. – Donald8274

+0

Я бы сказал, держитесь подальше от наследования/под-классов. Отдельные классы в порядке. –

+0

Я нашел способ заставить его работать, и я подумал, что это странный способ заставить его работать. Я добавил новый класс main и назвал его классом игрока в statup. – Donald8274

0

Вам не нужен основной метод для каждого класса. Вы можете решить проблему, переименовав метод на любую другую вещь, а затем назовите ее.

Статические методы не нужен экземпляр объекта:

public class MainClass { 
    /* args is the array of string commands passed as arguments 
     when the program is invoked */ 
    public static void main(String[] args) { 
     MyClass objRef = new MyClass(); 
     System.out.println(MyClass.myStaticMethod()); 
     //System.out.println(MyClass.nonStaticMethod()); // Cannot access a non-static method without an instance. 
     System.out.write(objRef.nonStaticMethod()); 
    } 

} 

class MyClass { 
    public static int myStaticMethod() { 
     return 1; 
    } 

    public int nonStaticMethod() { 
     return 2; 
    } 
} 

Там должен быть только один публичный класс каждого файла, и этот файл должен иметь такое же имя, как общественного класса.

Смежные вопросы