Using variables in different classes

Hi,
A very basic question!
i've got a 2d array in one class, which I want another class to be able to see. Is there any way I can do this in Java - if so, how? If not, is there a way around this?
Thanks

Or don't put it in a class, put it into an interface instead; have both classes impelement it.
~Bill

Similar Messages

  • Help with menus and variables in different classes.

    1) how do I change variables in different classes? My situation..
    I have a few tabbed panels/planes, that ask for different user inputs. I want the last tabbed panel/plane to have the inputs on 1 plane. Is that confusing?
    Code:
            JTabbedPane tp = new JTabbedPane();
            tp.addTab ("Kitchen", new KitchenPanel());
            tp.addTab ("Living Room", new LivingRoomPanel());
            tp.addTab ("Master Bedroom", new MasterBedPanel());
            tp.addTab ("Bedroom 1", new Bedroom1Panel());
            tp.addTab ("Bedroom 2", new Bedroom2Panel());
            tp.addTab ("Misc Use", new MiscPanel());
            tp.addTab ("Totals", new TotalsPanel());not the full thing obviously, but just so u see what im working with.
    2) How do popup menus work? I have a menu (File -> About | File -> How to Contact)
    I want The File->About menu item, to prompt a dialog
    The File -> How to to prompt a dialog
    Contact Menu(Not Item) to load a webpage
    thanks again for the help, and i hope its not to confusing
    Edited by: 2point2ek on May 25, 2009 9:51 PM

    It's better to think in terms of transferring data between object, rather than between classes.
    What you need is for the tab pane objects to have a reference to some common object to which the data is to be sent. This common object might be the total pane. It's generally better design to keep the data in separate objects from the presentation (in this case the totals pane), but at this stage that's probably just going to confuse you.
    The simplest way to get this reference in is to the pane objects is as a constructor argument, which the constructor of your pane objects saves in a field. As you create each pane you pass it a reference and it stores that reference for when it needs to save data.
    Then, when you click detect the action by which the user tells the program to store the data he's entered the pane class should call a method on the central data object, passing all the data from that pane. If there's a lot of it, wrap it up in an object (typically called a "data transfer object").
    The central data object would be responsible for dealing with this data, amending totals etc.. It might delegate responsibility for updating the display to a separate total pane object.

  • Using variable of one  class in another class

    what are the different ways in which we can access a variable defined in one class in some other class ,i am aware of making object of that class and using variable ,inheritance polymorphisms,is there any other way

    learnerpuneet wrote:
    i don't want to use objects of the respective class to access methods and variablesSo you've given up on OO already?
    Well okay, then declare everything static and you can use class names to access methods and variables.

  • Same parameter-map used on 2 different classes

    Greetings,
    If the same parameter-map (type connection or http) is used on two different policy-map classes, will that create a conflict in how traffic for each of serverfarms uses persistence or inactivity timeout (script 1)?
    Should we create a different instance of parameter-maps for each policy-map class (script 2)?
    Script 1
    parameter-map type connection inactivity_2000
    set timeout inactivity 2000
    parameter-map type http persistence-rebalance
    persistence-rebalance
    policy-map multi-match L4_POLICY
    class L3-4_VIP_A
    connection advanced-options inactivity_2000
    appl-parameter http advanced-options persistence-rebalance
    loadbalance policy L7_Serverfarm_A_Policy
    loadbalance vip inservice
    loadbalance vip icmp-reply active
    class L3-4_VIP_B
    connection advanced-options inactivity_2000
    appl-parameter http advanced-options persistence-rebalance
    loadbalance policy L7_Serverfarm_B_Policy
    loadbalance vip inservice
    loadbalance vip icmp-reply active
    Script 2
    parameter-map type connection L3-4_VIP_A_connection
    set timeout inactivity 2000
    parameter-map type connection L3-4_VIP_B_connection
    set timeout inactivity 2000
    parameter-map type http L3-4_VIP_A_http
    persistence-rebalance
    parameter-map type http L3-4_VIP_B_http
    persistence-rebalance
    policy-map multi-match L4_POLICY
    class L3-4_VIP_A
    connection advanced-options L3-4_VIP_A_connection
    appl-parameter http advanced-options L3-4_VIP_A_http
    loadbalance policy L7_Serverfarm_A_Policy
    loadbalance vip inservice
    loadbalance vip icmp-reply active
    class L3-4_VIP_B
    connection advanced-options L3-4_VIP_B_connection
    appl-parameter http advanced-options L3-4_VIP_B_http
    loadbalance policy L7_Serverfarm_B_Policy
    loadbalance vip inservice
    loadbalance vip icmp-reply active
    Thanks

    you can reuse the same parameter map.
    Gilles.

  • Using variables in different methods

    So I have to write a program that plays a game of craps for you. Here's the code:
    import java.util.*;
         class Craps{
             public static void main(String[] args)
               bet();
               dice();
               winnings();
            static void bet(){
               double bet;
                Scanner sc = new Scanner(System.in);
               System.out.println("How much money would you like to bet?");
                  if(sc.hasNextDouble())
                   bet = sc.nextDouble();
            public static void dice() {
                 int die1, die2, total;
                     die1 = (int)(Math.random() * 6) + 1;
                     die2 = (int)(Math.random() * 6) + 1;
                     total = die1 + die2;
              static void winnings(){
               while(total != 2 || total != 12 || total != 7 || total !=11 ){
                    total = points;
                    double winnings = points * bet;
                    System.out.println("You win $" +winnings);
                    return bet();
                 if(total = 2 || 12){
                     System.out.println("You lose, bet again.");
                     return bet();
                 if(total = 7  || 11){
                    System.out.println("You win $" +bet);
                    return bet();
       }I'm probably doing a few things wrong here, but it won't even compile because I can't figure out how to get the different methods to use the same variables.
    PS the point of the assignment is to do it with a bunch of methods, so while I could probably rewrite them without them, it would defeat the purpose.

    My compiler doesn't like it. Heres what my code is like now.
    import java.util.*;
         class Craps{
             public static void main(String[] args)
               static double bet;
               static int die1, die2, total;
               bet();
               dice();
               winnings();
            public static void bet(){
                Scanner sc = new Scanner(System.in);
               System.out.println("How much money would you like to bet?");
                  if(sc.hasNextDouble())
                   bet = sc.nextDouble();
            public static void dice() {
                     die1 = (int)(Math.random() * 6) + 1;
                     die2 = (int)(Math.random() * 6) + 1;
                     total = die1 + die2;
            public static void winnings(){
               while(total != 2 || total != 12 || total != 7 || total !=11 ){
                    total = points;
                    double winnings = points * bet;
                    System.out.println("You win $" +winnings);
                    return bet();
                 if(total = 2 || 12){
                     System.out.println("You lose, bet again.");
                     return bet();
                 if(total = 7  || 11){
                    System.out.println("You win $" +bet);
                    return bet();
       }And when i try and compile it this is what it says:
    craps.java:7: illegal start of expression
               static double bet;
               ^
    craps.java:8: illegal start of expression
               static int die1, die2, total;
               ^
    2 errors

  • Using variable in another class

    Im currently writting a Quiz program and i want to pass the varible holding the users score from the class "All.java" to "Results.java".
    Any ideas how i can do this?

    You can call a method in the other class and pass the value as an argument.
    You can call a setter method in the other class.
    You can move the knowledge and manipulation of that variable to the local class.
    You can use a helper class.
    All depends on what you're trying to do really, and I know that isn't much help. I struggled with the same question for a long time when I first used Java.

  • How to use get im different class?

    Hello, I am new to this java. I need your help, please
    I have Rental class that I use for my RentalApplication to run my Number of items rented & Total of Sale.
    However it gives me 0 instead of the number. Where did I write wrong code?
    public class Rental {
         //Declare variables
         public static final double COST_OF_NEW_RELEASES = 2.25;
         public static final double COST_OF_REGULAR_VIDEO = 1.00;
         public static final double COST_OF_DVDS = 2.98;
         public static final double COST_OF_GAMES = 4.50;
         private int NewReleases;
         private int RegularVideo;
         private int Dvds;
         private int Games;
         private Date timeOfSale;
         private int customerNumber;
         private String customerRental;
         //Constructor method
         public Rental(int theCustomerNumber) {
              timeOfSale = new Date();
              customerNumber = theCustomerNumber;
              NewReleases = 0;
              RegularVideo = 0;
              Dvds = 0;
              Games = 0;
              System.out.println(customerRental = "\nCustomer Number " + customerNumber);
         public Rental(
              int theNumberOfNewReleases,
              int theNumberOfRegularVideo,
              int theNumberOfDvds,
              int theNumberOfGames) {
              this.NewReleases = theNumberOfNewReleases;
              this.RegularVideo = theNumberOfRegularVideo;
              this.Dvds = theNumberOfDvds;
              this.Games = theNumberOfGames;
              this.timeOfSale = new Date();
         //Getters
         public int getNumberOfNewReleases() {
              return NewReleases;
         public int getNumberOfRegularVideo() {
              return RegularVideo;
         public int getNumberOfDvds() {
              return Dvds;
         public int getNumberOfGames() {
              return Games;
         //Other Methods
         public double rentalCost() {
              * Rental Cost()
              * creation date ("2/5/03" 1:30PM)
              return NewReleases * COST_OF_NEW_RELEASES
                   + RegularVideo * COST_OF_REGULAR_VIDEO
                   + Dvds * COST_OF_DVDS
                   + Games * COST_OF_GAMES;
         public String getCustomerRental() {
              return customerRental;
         public int totalAmountRented() {
              return NewReleases + RegularVideo + Dvds + Games;
         public Date getTimeOfSale() {
              return timeOfSale;
         public String getFormatteddatetimeOfSale() {
              DateFormat dateFormat = DateFormat.getDateInstance();
              return dateFormat.format(timeOfSale);
         public String getFormattedRentalCost() {
              * rentalCost()
              * creation date ("1/30/03" 1:30PM)
              NumberFormat dollarFormat = NumberFormat.getCurrencyInstance();
              return dollarFormat.format(rentalCost());
         public String toString() {
              String classDescription = "Thank You for renting";
              classDescription += " ";
              classDescription += "\nRental" + "[";
              classDescription += "New Releases = ";
              classDescription += NewReleases;
              classDescription += ", Number of Regular Video = ";
              classDescription += RegularVideo;
              classDescription += ", Number of DVDs = ";
              classDescription += Dvds;
              classDescription += ", Number of Games = ";
              classDescription += Games;
              classDescription += "]" + ", \n[" + "Time of Sale = ";
              classDescription += getFormatteddatetimeOfSale();
              classDescription += ", Rental Cost = ";
              classDescription += getFormattedRentalCost();
              classDescription += "]";
              return classDescription;
         public static void main(String[] args) {
              Rental theRental;
              theRental = new Rental(3, 1, 3, 1);
              System.out.println(theRental.toString());
         * Method findRentalItems.
         * @param thevideoId
         * @return RentalItems
         public static RentalItems findRentalItems(String thevideoId) {
              return null;
    This is my RentalApplication
    public class RentalApplication
         public static void main(String[] args)
              Rental theRental;
              RentalItems theRentalItems;
              VideoStore theVideoStore = new VideoStore();
              int customerNumber = 1;
              boolean newCustomer = true;
              boolean moreLookUps = true;
              String thevideoId;
              NumberFormat numberFormat = NumberFormat.getCurrencyInstance();
              DateFormat dateFormat = DateFormat.getDateTimeInstance();
              while (newCustomer)
                   theRental = new Rental(customerNumber);
                   while (moreLookUps)
                        thevideoId = JOptionPane.showInputDialog("Enter Video Id's");
                        theRentalItems = RentalItems.findRentalItems(thevideoId);
                        System.out.println(theRentalItems.displayRentalItems());
                        moreLookUps = getOption("Another Videos?");
                   theVideoStore.addRental(theRental);
                   System.out.println("Time of sale: "+ dateFormat.format(theRental.getTimeOfSale())
                                       + "\tNumber of items rented "
                                       + (theRental.totalAmountRented())
                                       + "\tTotal of Sale: "
                                       + numberFormat.format(
                                            theRental.rentalCost()));
                   newCustomer = getOption("Another Customer");
                   moreLookUps = true;
                   customerNumber++;
              System.out.println(theVideoStore.displayVideoStore());
              System.exit(0);
         public static int readInt(String prompt) {
              return Integer.parseInt(JOptionPane.showInputDialog(prompt));
         public static boolean getOption(String prompt) {
              int theNum;
              theNum = JOptionPane.showConfirmDialog(null, prompt);
              return (theNum == 0);

    In your RentalApplication main() method, you do the following:
    theRental = new Rental(customerNumber);which calls the
    public Rental(int theCustomerNumber)constructor.
    In that constructor, you initialize
    NewReleases = 0;
    RegularVideo = 0;
    Dvds = 0;
    Games = 0;But nowhere do you ever adjust those values. So the reason you're getting 0 back, I believe, is because that's what you set them to.

  • Using strings within different classes...help!!!!!!!

    Plz tell me how i can access a string that is defined in a another class.For example I have a string defined in a class i need to access it in a another class .The dot operator doesnt work unless the class in which string is defined is instantiated in the class where i need to access it.How do i do it then? .Iam not able to write a method to access the string (Smebody in the forum had suggested writing a method).Plz help me out?.The string is entered as user input during runtime .

    I should correct myself. Please post code that will also run as a program on our boxes. Also, in your current code Clicka doesn't have a Click object anywhere.
    One problem I see is in your first program Click is acting as an ActionListener, and your input string will only become available after the ActionListener has fired. So any program that wants the input String had better only request it after the listener has fired, has had its actionPerformed method called. So in this situation, how do you notify any interested programs that this has happened? One way is to use the observer pattern. This can be simply applied using a ChangeListener like so:
    Click.java
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.ArrayList;
    import java.util.List;
    import javax.swing.JOptionPane;
    import javax.swing.event.ChangeEvent;
    import javax.swing.event.ChangeListener;
    public class Click implements ActionListener
      private String input = "";
      List<ChangeListener> changeListeners = new ArrayList<ChangeListener>();
      public void actionPerformed(ActionEvent event)
        input = JOptionPane
            .showInputDialog("Enter the location of hex file (example C://new.txt");
        JOptionPane.showMessageDialog(null, "You have selected " + input);
        ChangeEvent e = new ChangeEvent(this);
        for (ChangeListener cl : changeListeners)
          cl.stateChanged(e);
      public void addChangeListener(ChangeListener cl)
        changeListeners.add(cl);
      public String getInput()
        return input;
    }UseClick.java
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import javax.swing.event.ChangeEvent;
    import javax.swing.event.ChangeListener;
    public class UseClick
      private JPanel mainPanel = new JPanel();
      private Click click;
      private JTextField textField = new JTextField(15);
      public UseClick()
        click = new Click();
        click.addChangeListener(new ChangeListener()
          public void stateChanged(ChangeEvent e)
            String input = click.getInput();
            textField.setText(input);
        JButton clickBtn = new JButton("Click");
        clickBtn.addActionListener(click);
        textField.setEditable(false);
        mainPanel.add(clickBtn);
        mainPanel.add(textField);
      public JPanel getMainPanel()
        return mainPanel;
      private static void createAndShowUI()
        JFrame frame = new JFrame("UseClick");
        frame.getContentPane().add(new UseClick().getMainPanel());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      public static void main(String[] args)
        java.awt.EventQueue.invokeLater(new Runnable()
          public void run()
            createAndShowUI();
    }

  • Resource needed for using  1 variable in 2 classes

    can anyone point me to a good resource on calling/using variables in another class? the problem i am facing is that i am using a for loop that has the string []splitresult variable used, i want to use this in another class aswell and dont no how,
    i really need a resource, preferably from the java turoials as they are easier to understsnd for me?
    thank you for that

    class MyClassA {
      int myVar = 3;
      public int getMyVar() {
         return this.myVar;
      public int setMyVar( int var ) {
        this.myVar = var;
    class MyClassB {
      public static void main ( String[] args ) {
         MyClassA myClassA = new MyClassA();
         int y = myClassA.getMyVar();
         myClassA.setMyVar( 44 );
         int z = myClassA.getMyVar();
         // if myVar was public you could do this, but this is NOT recommended, unless you have a good reason:
         int x = myClassA.myVar;
    }Edited by: ajmasx on Mar 15, 2008 10:08 AM

  • Using variables with lightboxes...

    Hi all,
    I am currently creating a scenario with two lightboxes. When you click a button the lightboxes will appear. When you click the 'x' button on both of the lightboxes, a button will appear, allowing the user to go onto the next slide. However, I have been unable to achieve this effect.
    I have been able to use variables across different slides, but not on the same slide. Any help would be appreciated. Thanks.

    Create a counter variable that you assign the value 0. Maybe it is even better to assign that value not in the definition but On Enter for the slide. For the moment you have two actions, those will have to be turned into conditional advanced actions with two decisions. Something like this:
    First decision 'Always'
    IF 1 is equal to 1      this is a mimicked standard action
       Show lightbox 1         
       Increment v_counter
    Second decision 'Checkit'
    IF v_counter is equal to 2
       Show Gr_Buttons
    I used a group, didn't want to type too much, you can group the 3 buttons.

  • Can I share Attributes/Variables between 2 different Class Driver Sessions?

    I am designing a Simulator of Instrumentation following these steps:
    1) re-programming, re-compiling, and re-building the DLLs from the advanced class simulation drivers included in IVI Driver Toolset 2.0 using LabWindows/CVI 7.0;
    2) then i create a VI in LabVIEW 7.0 which calls an IVI Class Driver obtaining the desired simulated output data.
    My problem is that I need to share variables between different DLLs in LabVIEW.
    I want to simulate a circuit which consists of a battery and a resistor. I've got 2 instruments: a DC Power Supply and a Digital Multimeter.
    The DC Power Supply acts as the battery providing a certain voltage level, and the Multimeter measures the Voltage and the Current in the resistor.
    I've designed a VI in LabVIEW which uses 2 different sessions: one which calls the class driver IviDCPwr, and the other one which calls IviDmm.
    I wish to be able to access the attributes from "nisDCPwr.c" in the file "nisDmm.c".
    For example, to write a line like this:
    Ivi_GetAttributeViReal64 (ViSession vi, ViConstString channelName, NISDCPWR_ATTR_MEASUREMENT_BASEV, 0, &reading));
    inside the source code "nisDmm.c" of the advanced class simulation driver.
    The problem is that the only ViSession accessible from nisDmm is the handle from the Digital Multimeter, but not from DC Power Supply.
    Would this be possible? Is it "legal"?
    I've tried another approach through the declaration of external variables, but unfortunately I get a run-time error in LabVIEW.
    The only solution I've found is using auxiliary files going between, through the functions included in the Low Level I/O Library .
    Nevertheless, the solution proposed above would result much more convenient, faster and safer in my application.
    I hope everyone has understood my question, and anyone can help.
    THANK YOU VERY MUCH FOR YOUR TIME!!!

    Doesn't anyone have an answer?
    Or any proposal?
    Or even a clue?
    THANKS!

  • How to use the different class for each screen as well as function.

    Hi Experts,
    How to use the different class for each screen as well as function.
    With BestRegards,
    M.Thippa Reddy.

    Hi ThippaReddy,
    see this sample code
    Public Class ClsMenInBlack
    #Region "Declarations"
        'Class objects
        'UI and Di objects
        Dim objForm As SAPbouiCOM.Form
        'Variables
        Dim strQuery As String
    #End Region
    #Region "Methods"
        Private Function GeRate() As Double
                Return Double
        End Function
    #End Region
    Public Sub SBO_Appln_MenuEvent(ByRef pVal As SAPbouiCOM.MenuEvent, ByRef BubbleEvent As Boolean)
            If pVal.BeforeAction = True Then
                If pVal.MenuUID = "ENV_Menu_MIB" Then
                End If
            Else ' Before Action False
                End If
        End Sub
    #End Region
    End Class
    End Class
    Rgds
    Micheal
    Vasu Anna Regional Feeling a???? Just Kidding
    Edited by: micheal willis on Jul 27, 2009 5:49 PM
    Edited by: micheal willis on Jul 27, 2009 5:50 PM

  • Using Variables/Arrays from one class in another

    Hello all,
    First, to explain what I am attempting to create, is a program that will accept input of employee names and hours worked into an array. The first class will accept a command line argument when invoked. If the argument is correct, it will call another class that will gather information from the user via an input box. After all names and hours have been input for employees, this class will calculate the salary based upon the first letter of each employee name and print the total hours, salary, etc. for each employee.
    What I need to do now is to split the second class into two: one that will gather the data and another that will calculate and print the data. Yes, this is an assignment. However, I am trying to learn and I have gotten this far, but I am stuck on how to get a class to be able to use an array/variables from another class.
    I realize the below code isn't exactly cleaned up...yet.
    Code for AverageSalaryGather class:
    import javax.swing.JOptionPane; // uses class JOptionPane
    import java.lang.reflect.Array;     
    import java.math.*;
    public class AverageSalaryGather {
         public static void gatherData() {     
              char[] alphaArray = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','x','y','z'};
              String[][] empInfoArray = new String[100][4];
              String[] empNameArray = new String[100];
              String finalOutput = "Name - Rate - Hours - Total Pay\n";
              String averageHoursOutput = "Average Hours Worked:\n";
              String averageSalaryOutput = "Average Hourly Salary:\n";
              String averageGroupSalaryOutput = "Average Group Salary:\n";
                        String[] rateArray = new String[26];
                        char empNameChar = 'a';
              int empRate = 0;
              int payRate = 0;
                        for (int i = 0; i < 26; i++) {
                   payRate = i + 5;
                   rateArray[i] = Integer.toString(payRate);
                        int countJoo = 0;
              while (true) {
                   String namePrompt = "Please enter the employee name: ";
                   String empName = JOptionPane.showInputDialog(namePrompt);
                                  if (empName == null | empName.equals("")) {
                        break;
                   else {
                        empInfoArray[countJoo][0] = empName;
                        for (int i = 0; i < alphaArray.length; i++) {
                             empNameChar = empName.toLowerCase().charAt(0);
                                                      if (alphaArray[i] == empNameChar) {
                                  empInfoArray[countJoo][1] = rateArray;
                                  break;
                        countJoo++;
              // DecimalFormat dollarFormat = new DecimalFormat("$#0.00");
              for (int i = 0; i < empInfoArray.length; i++) {
                   if (!(empInfoArray[i][0] == null)) {
                        String hourPrompt = "Please enter hours for " + empInfoArray[i][0] + ": ";
                        String empHours = JOptionPane.showInputDialog(hourPrompt);
                        int test = 0;
                        empInfoArray[i][2] = empHours;
                        // convert type String to double
                        //double tmpPayRate = Double.parseDouble(empInfoArray[i][1]);
                        //double tmpHours = Double.parseDouble(empInfoArray[i][2]);
                        //double tmpTotalPay = tmpPayRate * tmpHours;
                        // create via a string in empInfoArray
                             BigDecimal bdRate = new BigDecimal(empInfoArray[i][1]);
                             BigDecimal bdHours = new BigDecimal(empInfoArray[i][2]);
                             BigDecimal bdTotal = bdRate.multiply(bdHours);
                             bdTotal = bdTotal.setScale(2, RoundingMode.HALF_UP);
                             String strTotal = bdTotal.toString();
                             empInfoArray[i][3] = strTotal;
                        //String strTotalPay = Double.toString(tmpTotalPay);
                        //empInfoArray[i][3] = dollarFormat.format(tmpTotalPay);
                        else {
                             break;
              AverageSalaryCalcAndPrint averageSalaryCalcAndPrint = new AverageSalaryCalcAndPrint();
              averageSalaryCalcAndprint.calcAndPrint();
    Code for AverageSalaryCalcAndPrint class (upon compiling, there are more than a few complie errors, and that is due to me cutting/pasting the code from the other class into the new class and the compiler does not know how to access the array/variables from the gatherData class):
    import javax.swing.JOptionPane; // uses class JOptionPane
    import java.lang.reflect.Array;
    import java.math.*;
    public class AverageSalaryCalcAndPrint
         public static void calcAndPrint() {     
              AverageSalaryGather averageSalaryGather = new AverageSalaryGather();
              double totalHours = 0;
              double averageHours = 0;
              double averageSalary = 0;
              double totalSalary = 0;
              double averageGroupSalary = 0;
              double totalGroupSalary = 0;
              int countOfArray = 0;
              for (int i = 0; i < empInfoArray.length; i++) {
                   if (!(empInfoArray[0] == null)) {
                        totalSalary = totalSalary + Double.parseDouble(empInfoArray[i][1]);
                        totalHours = totalHours + Double.parseDouble(empInfoArray[i][2]);
                        totalGroupSalary = totalGroupSalary + Double.parseDouble(empInfoArray[i][3]);
                        countOfArray = i;
              averageHours = totalHours / (countOfArray + 1);
              averageSalary = totalSalary / (countOfArray + 1);
              averageGroupSalary = totalGroupSalary / (countOfArray + 1);
              String strAverageHourlySalary = Double.toString(averageSalary);
              String strAverageHours = Double.toString(averageHours);
              String strAverageGroupSalary = Double.toString(averageGroupSalary);
              for (int i = 0; i < empInfoArray.length; i++) {
                   if (!(empInfoArray[i][0] == null)) {
                        finalOutput = finalOutput + empInfoArray[i][0] + " - " + "$" + empInfoArray[i][1] + "/hr" + " - " + empInfoArray[i][2] + " - " + "$" + empInfoArray[i][3] + "\n";
              averageHoursOutput = averageHoursOutput + strAverageHours + "\n";
              averageSalaryOutput = averageSalaryOutput + strAverageHourlySalary + "\n";
              averageGroupSalaryOutput = averageGroupSalaryOutput + strAverageGroupSalary + "\n";
              JOptionPane.showMessageDialog(null, finalOutput + averageHoursOutput + averageSalaryOutput + averageGroupSalaryOutput, "Totals", JOptionPane.PLAIN_MESSAGE );

    Call the other class's methods. (In general, you
    shouldn't even try to access fields from the other
    class.) Also you should be looking at an
    instance of the other class, and not the class
    itself, generally.Would I not call the other classes method's by someting similar as below?:
    AverageSalaryCalcAndPrint averageSalaryCalcAndPrint = new AverageSalaryCalcAndPrint();
              averageSalaryCalcAndprint.calcAndPrint(); Well... don't break down classes based on broad steps
    of the program. Break them down by the information
    being managed. I'm not expressing this well...Could you give an example of this? I'm not sure I'm following well.
    Anyway, you want one or more objects that represent
    the data, and operations on that data. Those
    operations include calculations on the data. Other
    classes might represent the user interface, and
    different output types (say, a file versus the
    console).Yes, the requirements is to have a separate class to gather the data, and then another class to calculate and print the data. Is this what you mean in the above?

  • Using a variable from one class in another

    For learning purposes, I thought I'd have a stab at making a role-playing RPG.
    The first class I made was the Player class;
    public class Player
         public static void main(String[] args)
              // [0] being base points and  [1] being skill points
              int[] points = {50, 10};
              // Elements in statNames are relevent to stats, so stats[0] is health, and so on
              String[] statNames = {"Health", "Mana", "Attack", "Magic", "Craft"};
              int[] stats = new int[5];
         public static String setName()
              Scanner input = new Scanner(System.in);
              System.out.print("Character name: ");
              String name = input.nextLine();
              return name;
         public static void setHealth(int[] points, int[] stats)
              Scanner input = new Scanner(System.in);
              System.out.print("Health (" + points[0] + " base points remanining): ");
              stats[0] = input.nextInt();
              points[0] -= stats[0];
            public static void setMana(int[] points, int[] stats)
              Scanner input = new Scanner(System.in);
              System.out.print("Mana (" + points[0] + " base points remanining): ");
              stats[1] = input.nextInt();
              points[0] -= stats[1];
         public static void setAttack(int[] points, int[] stats)
              Scanner input = new Scanner(System.in);
              System.out.print("Attack (" + points[1] + " skill points remanining): ");
              stats[2] = input.nextInt();
              points[1] -= stats[2];
         public static void setMagic(int[] points, int[] stats)
              Scanner input = new Scanner(System.in);
              System.out.print("Magic (" + points[1] + " skill points remanining): ");
              stats[3] = input.nextInt();
              points[1] -= stats[3];
         public static void setCraft(int[] points, int[] stats)
              Scanner input = new Scanner(System.in);
              System.out.print("Craft (" + points[1] + " skill points remanining): ");
              stats[4] = input.nextInt();
              points[1] -= stats[4];
         public static void setStats(int[] points, int[] stats)
              setHealth(points, stats);
              setMana(points, stats);
              setAttack(points, stats);
              setMagic(points, stats);
              setCraft(points, stats);
         public static void charSummary(String name, String[] statNames, int[] stats)
              System.out.println("\n------  " + name);
              for(int index = 0; index < stats.length; index++)
                   System.out.println(statNames[index] + ":\t" + stats[index]);
    }And that would be used in the Play class;
    public class Play
         public static void main(String[] args)
              Player player = new Player();
              String name = player.setName();
              player.setStats(points, stats);
         }     But I'm not sure how the Play class will get the arrays from the Player class. I tried simply putting public in front of the them, for example;
    public String[] statNames = {"Health", "Mana", "Attack", "Magic", "Craft"};But I get an illegal start of expression error.
    I may have taken the wrong approach to this all together, I'm completely new, so feel free to suggest anything else. Sorry for any ambiguity.
    Edited by: xcd on Jan 6, 2010 8:12 AM
    Edited by: xcd on Jan 6, 2010 8:12 AM

    HI XCD ,
    what about making Player class as
    public class Player
              // [0] being base points and  [1] being skill points
              int[] points = {50, 10};
              // Elements in statNames are relevent to stats, so stats[0] is health, and so on
              public String[] statNames = {"Health", "Mana", "Attack", "Magic", "Craft"};
              int[] stats = new int[5];
         public String setName()
              Scanner input = new Scanner(System.in);
              System.out.print("Character name: ");
              String name = input.nextLine();
              return name;
         public void setHealth(int[] points, int[] stats)
              Scanner input = new Scanner(System.in);
              System.out.print("Health (" + points[0] + " base points remanining): ");
              stats[0] = input.nextInt();
              points[0] -= stats[0];
            public void setMana(int[] points, int[] stats)
              Scanner input = new Scanner(System.in);
              System.out.print("Mana (" + points[0] + " base points remanining): ");
              stats[1] = input.nextInt();
              points[0] -= stats[1];
         public void setAttack(int[] points, int[] stats)
              Scanner input = new Scanner(System.in);
              System.out.print("Attack (" + points[1] + " skill points remanining): ");
              stats[2] = input.nextInt();
              points[1] -= stats[2];
         public void setMagic(int[] points, int[] stats)
              Scanner input = new Scanner(System.in);
              System.out.print("Magic (" + points[1] + " skill points remanining): ");
              stats[3] = input.nextInt();
              points[1] -= stats[3];
         public void setCraft(int[] points, int[] stats)
              Scanner input = new Scanner(System.in);
              System.out.print("Craft (" + points[1] + " skill points remanining): ");
              stats[4] = input.nextInt();
              points[1] -= stats[4];
         public void setStats(int[] points, int[] stats)
              setHealth(points, stats);
              setMana(points, stats);
              setAttack(points, stats);
              setMagic(points, stats);
              setCraft(points, stats);
         public void charSummary(String name, String[] statNames, int[] stats)
              System.out.println("\n------  " + name);
              for(int index = 0; index < stats.length; index++)
                   System.out.println(statNames[index] + ":\t" + stats[index]);
         }and Play class
    public class Play
         public static void main(String[] args)
              Player player = new Player();
              String name = player.setName();
              player.setStats(points, stats);
         }Now you can access names , you can't assign keyword to variable into method scope , make it class variable .
    Hope it help :)

  • Using a variable from one class to another

    Hi !
    I've a class called ModFam (file ModFam.java) where I define a variable as
    protected Connection dbconn;
    Inside ModFam constructor I said:
    try
    String url = "jdbc:odbc:baselocal";
    Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );
    dbconn = DriverManager.getConnection(url);
    System.err.println("Connection successful");
    } ..... rest of code
    This class define a TabbedPane as follows:
    tabbedPane.addTab("Welcome",null,new Familias(),"Familias");
    As you can see it call a new instance of the Familias class (file Familias.java).
    This constructor will try to connect with the DB to populate a combo box with some data retireved from the DB.
    If I do
    Statement stmt;
    stmt = dbconn.createStatement();
    inside Familias constructor I receive the message
    Familias.java:50: cannot resolve symbol
    symbol : variable dbconn
    location: class fam.Familias
    stmt = dbconn.createStatement();
    at compile time.
    While I can�t use a variable defined as "protected" in one class of my package on another class of the same package ?
    How could I do ?
    Thanks in advance
    <jl>

    Familias doesn't have a reference to ModFam or the Connection.
    So change the constructor in Familias to be
    public class Familias {
      private ModFam modFam;
      public Familias(ModFam m) {
        modFam = m;
    // ... somewhere else in the code
    Statement stmt = modFam.dbconn.createStatement();
    }or
    public class Familias {
      private Connection dbconn;
      public Familias(Connection c) {
        dbconn = c;
    // ... somewhere else in the code
    Statement stmt = dbconn.createStatement();
    }And when you instantiate Familias it should then be
    new Familias(this) // ModFam reference
    or
    new Familias(dbconn)

Maybe you are looking for

  • Music video into itunes

    okay I have a music video that I didn't get from itunes because itunes doesn't have it but I am unable to get the video into my playlist the only place it is willing to go is in the movies playlist. I am trying to get it into the music videos smart p

  • Report for pending release

    Hi All, Can you please tell me which report I can use to see pending PO relese list for a particular person. thanks John

  • How to convert photo shop docs to .pdf

    I accidently used photo shop to opened a .pdf file and now all of my .pdf file have to be imported to photo shop to open and I am not able to get all the pages.  How am I able to correct this problem and use Adobe Acrobat to open the .pdf file?

  • While installing weblogic 6.1

    While installing weblogic 6.1 i am seeing the install anywhere message with 100 % and after it stops doesn;t knwo whats wrong with it..i am using windows xp

  • Would I be able to boot from USB on my Macbook Pro if my logic board was damaged?

    My macbook pro recently started to slow down, programs freeze, etc. Odd behavior. So I decided to install a clean version of os. My hard drive came up as corrupt, I need to repair. So I did that. And was unable to install to os. It starts up and then