2016-03-23 11 views
-1

ile değiştiriniz. If deyiminde kullanılan bir int'nin değerini bir anahtar deyiminde değiştirmeye çalışıyorum, ancak dışarıdaki değeri nasıl değiştireceğimi anlayamıyorum Değişkenin yeni bir örneğini oluşturmak.if deyimini bir durum anahtar deyiminde

Sorunun olduğu sınıf, ana sınıfta, sınıfın geri kalanı kod için gereklidir, ancak ilgili değildir. Ancak FramePanel Sınıfı, kullanıcı gui komut kutusuna bir sayı girdiğinde kararChooser yöntemini başlatır.

Tam kodum aşağıda.

import java.awt.*; 
import java.awt.event.ActionEvent; 
import java.awt.event.KeyEvent; 
import java.util.Random; 
import javax.swing.*; 

@SuppressWarnings("serial") 
public class FramePanel extends JPanel 
{ 
    /////Setting Positioning///// 

    // rows and cols for jtextarea 
    private static final int CURRENT_AREA_ROWS = 20; 
    private static final int CURRENT_AREA_COLS = 40; 

    // columns for command jtextfied 
    private static final int COMMANDS_FIELD_COLS = 50; 

    // size of GUI component gaps 
    private static final int EB_GAP = 1; 

    private String inventoryString() 
    { 
     return ("Inventory:" + 
       "\n- " + 
       "\n- " + 
       "\n- " + 
       "\n- " + 
       "\n- " + 
       "\n- " + 
       "\n- " + 
       "\n- " + 
       "\n- " + 
       "\n- "); 
    } 

    private String startString() 
    { 
     return ("Welcome to Warlock of Firetop Mountain! This game was coded by Thomas Thorburn and the story line was written by Ian Livingstone and Steve Jackson. To get started, click 'New Game' or load a save. If you get stuck click the 'Help' button or read the 'Help and Information' document.\n\nLet the Adventure Begin!"); 
    } 
    private EnterAction enterAction = new EnterAction("Enter"); 

    public static JTextArea currentTextArea = new JTextArea(CURRENT_AREA_ROWS, CURRENT_AREA_COLS); 
    public static JTextField commandsField = new JTextField(COMMANDS_FIELD_COLS); 
    public static JTextArea inventoryTextArea = new JTextArea(CURRENT_AREA_ROWS, CURRENT_AREA_COLS); 



    public FramePanel() 
    { 

     JPanel topBtnPanel = new JPanel(new GridLayout(1, 0)); 
     { 
      topBtnPanel.add(new JButton(new HelpAction("Help", KeyEvent.VK_X))); 
      topBtnPanel.add(new JButton(new RollAction("Roll Dice", KeyEvent.VK_X))); 
      topBtnPanel.add(new JButton(new NewGameAction("New Game", KeyEvent.VK_X))); 
      topBtnPanel.add(new JButton(new SaveAction("Save", KeyEvent.VK_X))); 
      topBtnPanel.add(new JButton(new LoadAction("Load", KeyEvent.VK_X))); 
     } 

     JPanel characteristicsPanel = new JPanel(new GridBagLayout()); 
     { 
      GridBagConstraints gbc = new GridBagConstraints(); 
      gbc.anchor = GridBagConstraints.WEST; 
      gbc.fill = GridBagConstraints.HORIZONTAL; 
      gbc.gridx = 1; 
      gbc.gridy = 0; 
      characteristicsPanel.add(new JTextField("20"), gbc); 
      gbc.gridy ++; 
      characteristicsPanel.add(new JTextField("20"), gbc); 
      gbc.gridy ++; 
      characteristicsPanel.add(new JTextField("20"), gbc); 
      gbc.gridy ++; 
      characteristicsPanel.add(new JTextField("20"), gbc); 
      gbc.gridy ++; 
      characteristicsPanel.add(new JTextField("20"), gbc); 
      gbc.gridy ++; 
      characteristicsPanel.add(new JTextField("20"), gbc); 
      gbc.gridy ++; 
      characteristicsPanel.add(new JTextField("20"), gbc); 
      gbc.gridy ++; 

      gbc.anchor = GridBagConstraints.EAST; 
      gbc.gridx = 0; 
      gbc.gridy = 0; 
      characteristicsPanel.add(new JLabel("SKILL: "), gbc); 
      gbc.gridy ++; 
      characteristicsPanel.add(new JLabel("STAMINA: "), gbc); 
      gbc.gridy ++; 
      characteristicsPanel.add(new JLabel("LUCK: "), gbc); 
      gbc.gridy ++; 
      characteristicsPanel.add(new JLabel("GOLD: "), gbc); 
      gbc.gridy ++; 
      characteristicsPanel.add(new JLabel("JEWELS: "), gbc); 
      gbc.gridy ++; 
      characteristicsPanel.add(new JLabel("POTIONS: "), gbc); 
      gbc.gridy ++; 
      characteristicsPanel.add(new JLabel("PREVISIONS: "), gbc); 
      gbc.gridy ++; 
     } 

     inventoryTextArea.setWrapStyleWord(true); 
     inventoryTextArea.setLineWrap(true); 
     inventoryTextArea.setEditable(true); 
     inventoryTextArea.append(inventoryString()); 
     JScrollPane imgListPane = new JScrollPane(inventoryTextArea); 
     imgListPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); 

     JPanel rightPanel = new JPanel(new BorderLayout(EB_GAP, EB_GAP)); 
     rightPanel.add(topBtnPanel, BorderLayout.PAGE_START); 
     rightPanel.add(imgListPane, BorderLayout.CENTER); 
     rightPanel.add(characteristicsPanel, BorderLayout.LINE_END); 

     currentTextArea.setWrapStyleWord(true); 
     currentTextArea.setLineWrap(true); 
     currentTextArea.setFocusable(false); 
     currentTextArea.append(startString()); 
     JScrollPane taScrollPane = new JScrollPane(currentTextArea); 
     taScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); 

     JPanel centerPanel = new JPanel(new BorderLayout()); 
     centerPanel.add(taScrollPane, BorderLayout.CENTER); 
     centerPanel.add(rightPanel, BorderLayout.LINE_END); 

     JPanel commandsPanel = new JPanel(); 
     commandsPanel.setLayout(new BoxLayout(commandsPanel, BoxLayout.LINE_AXIS)); 
     commandsPanel.add(commandsField); 
     commandsPanel.add(Box.createHorizontalStrut(EB_GAP)); 
     commandsPanel.add(new JButton(enterAction)); 
     commandsPanel.add(Box.createHorizontalStrut(EB_GAP)); 
     commandsField.setAction(enterAction); // use same action for button and 


     setBorder(BorderFactory.createEmptyBorder(EB_GAP, EB_GAP, EB_GAP, EB_GAP)); 
     setLayout(new BorderLayout(EB_GAP, EB_GAP)); 
     add(centerPanel, BorderLayout.CENTER); 
     add(commandsPanel, BorderLayout.PAGE_END); 
    } 


    /////////Buttons///////// 
    //Enter Button Action 
    private class EnterAction extends AbstractAction 
    { 
     public EnterAction(String name) 
     { 
      super(name); 
     } 

     @Override 
     public void actionPerformed(ActionEvent e) 
     { 
      Main mainChoices = new Main();//Allowing me to call Main 
      mainChoices.decisionChooser();//Calling up decisionChooser method 
     } 
    } 

    //Help Action 
    private class HelpAction extends AbstractAction 
    { 
     public HelpAction (String name, int mnemonic) 
     { 
      super(name); 
      putValue(MNEMONIC_KEY, mnemonic); 
     } 

     @Override 
     public void actionPerformed(ActionEvent e) 
     { 
      currentTextArea.append("\n\n" + "Welcome to Warlock of Firetop Mountain! To navigate the story line just enter the relevant page number in the text box below, To make this game as authentic as possiable to the original game, all combat stats and inventory are controlled by the user. \n\nTo Save, Load or start a New Game, use the corresponding buttons in the top right of the window. To roll the dice you also click the 'Roll Dice' button. This will print the two dice rolls in your storyline box. For more information, please refer to the help and information guide provided with this program." + "\n \n"); 
     } 
    } 

    //New Game Button and Action 
    private class NewGameAction extends AbstractAction 
    { 
     public NewGameAction (String name, int mnemonic) 
     { 
      super(name); 
      putValue(MNEMONIC_KEY, mnemonic); 
     } 

     @Override 
     public void actionPerformed(ActionEvent e) 
     { 
      currentTextArea.setText(startString()); 
     } 
    } 

    //Load Button and Action 
    private class LoadAction extends AbstractAction 
    { 
     public LoadAction (String name, int mnemonic) 
     { 
      super(name); 
      putValue(MNEMONIC_KEY, mnemonic); 
     } 

     @Override 
     public void actionPerformed(ActionEvent e) 
     { 
      OpenFile of = new OpenFile(); 

      try 
      { 
       of.PickMe(); 
      } 
      catch (Exception e1) 
      { 
       e1.printStackTrace(); 
      } 
      currentTextArea.setText(of.sb.toString()); 
     } 
    } 

    //Save Button and Action 
    private class SaveAction extends AbstractAction 
    { 
     public SaveAction (String name, int mnemonic) 
     { 
      super(name); 
      putValue(MNEMONIC_KEY, mnemonic); 
     } 

     @Override 
     public void actionPerformed(ActionEvent e) 
     { 
      System.out.print("yo3"); 
     } 
    } 

    //Exit Button and Action 
    private class ExitAction extends AbstractAction 
    { 
     public ExitAction(String name, int mnemonic) 
     { 
      super(name); 
      putValue(MNEMONIC_KEY, mnemonic); 
     } 

     @Override 
     public void actionPerformed(ActionEvent e) 
     { 
      Component source = (Component) e.getSource(); 
      Window win = SwingUtilities.getWindowAncestor(source); 
      win.dispose(); 
     } 
    } 

    //Roll Button Action 
    private class RollAction extends AbstractAction 
    { 
     public RollAction(String name, int mnemonic) 
     { 
      super(name); 
      putValue(MNEMONIC_KEY, mnemonic); 
     } 

     @Override 
     public void actionPerformed(ActionEvent e) 
     { 
      Random r = new Random(); 

      int diceRoll1=r.nextInt(6); //Generates random number 
      int diceRoll2=r.nextInt(6); 


      diceRoll1 = diceRoll1 + 1; //Changes range from 0-5 to 1-6 
      diceRoll2 = diceRoll2 + 1; 

      currentTextArea.append("You have rolled a " + diceRoll1 + " and a " + diceRoll2 + "!" + "\n"); 
     } 
    } 


    /////////GUI Setup///////// 
    //Making and choosing settings for frame. 
    private static void createAndShowGUI() 
    { 
     FramePanel mainPanel = new FramePanel(); 

     JFrame frame = new JFrame("Warlock of Firetop Mountain"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setResizable(true); 
     frame.setLocationRelativeTo(null); 
     frame.getContentPane().add(mainPanel); 
     frame.pack(); 
     frame.setLocationRelativeTo(null); 
     frame.setVisible(true); 
    } 


    /////////Getters and Setters///////// 
    //Getter for currentTextArea 
    public static JTextArea getTextArea() 
    { 
     return currentTextArea; 
    } 


    /////////Run Later///////// 
    public static void runLater() 
    { 
     SwingUtilities.invokeLater(new Runnable() 
     { 
      public void run() 
      { 
       createAndShowGUI(); 
      } 
     }); 
    } 
} 

OpenFile Sınıf:

public class Main 
{ 
    public static void main(String[] args) 
    { 
     FramePanel.runLater(); 
     StoryArray.main(); 
    } 

    public int a1; 
    public int a2; 
    public int a3; 
    public int a4; 
    public int a5; 
    public int textNumber; 
    public String chosenText; 


    public void decisionChooser() 
    { 
     String inputText = FramePanel.commandsField.getText(); 
     FramePanel.commandsField.setText(null); 
     try 
     { 
      textNumber = Integer.parseInt(inputText); 
      textNumber = textNumber - 1; 

      if (textNumber == a1 || textNumber == a2 || textNumber == a3 || textNumber == a4 || textNumber == a5) 
      { 
       System.out.println(textNumber + " in If"); 

       System.out.println("Entering switch"); 
       switch (textNumber) 
       { 
        case 0: 
         a1 = 70; // this will change a1 for in the if statement 
         chosenText = StoryArray.storyLine[textNumber]; 
         FramePanel.currentTextArea.append(chosenText + "\n"); 
         break; 

        case 70: 
         a1 = 281; 
         chosenText = StoryArray.storyLine[textNumber]; 
         FramePanel.currentTextArea.append(chosenText + "\n"); 
         break; 

        default: 
         break; 
       } 
      } 
      else 
      { 
       FramePanel.currentTextArea.append("\nPlease choose a valid page number!\n"); 
      } 
      System.out.println("Out of If statement"); 
     } 
     catch (NumberFormatException NFE) 
     { 
      FramePanel.currentTextArea.append("Please Enter the Page number" + "\n"); 
     } 
     System.out.println("looped"); 
    } 
} 

FramePanel Sınıfı:

Ana Sınıfı: eğer bulmak ve söz konusu ifadeleri geçecektir nerede ana sınıftır altında

import javax.swing.*; 
import java.util.Scanner; 

public class OpenFile 
{ 
    JFileChooser loadFile = new JFileChooser(); 
    StringBuilder sb = new StringBuilder(); 

    public void PickMe() throws Exception 
    { 
     if(loadFile.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) 
     { 
      java.io.File file = loadFile.getSelectedFile(); 


      Scanner input = new Scanner(file); 

      while (input.hasNext()) 
      { 
       sb.append(input.nextLine()); 
       sb.append("\n\n"); 
      } 
      input.close(); 

     } 
     else 
     { 
      sb.append("\n\n" + "No File Selected! \n\n"); 

     } 
    } 
} 

StoryArray Sınıfı (Dizgi miktarı nedeniyle kısaltıldı):

public class StoryArray 
{ 
    public static String storyLine[] = null ; 
    public static String[] getStoryLine() 
    { 
     return storyLine; 
    } 
    public static void main() 
    { 
     //String[] storyLine; 
     storyLine = new String[399]; 
     storyLine[0] = ("test1"); 
     storyLine[1] = ("test2"); 
     storyLine[2] = ("test 3"); 
     storyLine[18] = ("test4"); 

     storyLine[69] = ("Test5"); 
     storyLine[70] = ("Test6"); 
     storyLine[71] = ("Test7"); 
     storyLine[73] = ("Test8"); 
    } 
} 
+1

Hangi değişken değiştirmek çalışıyorsun? –

+1

Lütfen kodunuzun beklenen davranışını ve bunun yerine neler olduğunu açıklayın. – BPS

+0

Oh Üzgünüm id idideyken bir şeyi silmeden test edince kodu hızlıca düzenleyeceğim, ne yapmak istediğimde 0, veya 70, a1, 2, 3, 4 veya 5 değerini değiştirecek bir açıklama var. Bir sonraki ifade için –

cevap

0

Değişken bir genel yapmanın onu bir sınıf değişkeni haline getirmediğini fark ettim. Bu, döngüyü çalıştırdığım her seferde, değişkenin yeni bir örneğini oluşturacaktır. Bunu değiştirmek ve bir sınıf değişkeni yapmak için bunu statik olarak bildirmek zorunda kaldım, bu sadece bir örnek olabileceği anlamına geliyordu, bu nedenle her zaman döngüyü çalıştırdım ve anahtar deyimindeki değerleri değiştirdi. döngü de.

Bu bunu beyan etmek zorunda nasıl:

public static int textNumber; 
İlgili konular