[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

arrays

Posted on 2006-05-29
9
Medium Priority
?
219 Views
Last Modified: 2010-03-31
I am writing a program to prompt a user to select how they would like to sort from any of 3 arrays and then display the choices in a text field.  i am getting a compile error of ''non-static variable service cannot be referenced from a static context''. I looked on the java.sun website and have set up the sort as the instructions say to, at least from what i see. I have posted the code below. What is wrong with the program?

1st program- gui-

import javax.swing.*;
import java.awt.*;

public class HairSalon extends JFrame {

HairSalonSupport HairSalonSupport=new HairSalonSupport(this);

//sets up rows for gui
JPanel row10 = new JPanel();
JLabel amntLabel = new JLabel("We Cut Salon", JLabel.LEFT);
//public JTextField serviceField = new JTextField(10);


JPanel row20 =new JPanel();
JComboBox options = new JComboBox();
JLabel optionsLabel = new JLabel();
JLabel lbltype= new JLabel("Salon Services",JLabel.LEFT);
JTextField years                  = new JTextField(2);

JPanel row30 = new JPanel();
JLabel sortType= new JLabel("Sort by one of the following:",JLabel.LEFT);
public JButton serviceButton = new JButton("Service");
public JButton priceButton = new JButton("Price");
public JButton timeButton = new JButton("Time");

JPanel row40 = new JPanel();
JLabel paymtLabel = new JLabel("Service Price");
public JTextField paymtField = new JTextField();

JPanel row50 = new JPanel();
JLabel lblservice= new JLabel("Service"+ "\t",JLabel.LEFT);
JLabel lblPrice= new JLabel("Price"+ "\t",JLabel.LEFT);
JLabel lblTime= new JLabel("Time"+ "\t",JLabel.LEFT);
//JLabel lblBalance= new JLabel("Balance"+ "\t",JLabel.LEFT);

JPanel row60 = new JPanel();
JTextArea textField = new JTextArea(8, 40);

JPanel row70=new JPanel();
public JButton calButton = new JButton("Calculate");
public JButton resetButton = new JButton("Reset");
public JButton endButton = new JButton("End");



public HairSalon() {

super("We Cut Salon");
setSize(650,500);
setLocation(250,60);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Font f = new Font ("Arial", Font.PLAIN, 30);
Font b = new Font ("Arial", Font.BOLD, 16);
FlowLayout layout = new FlowLayout();
Container pane = getContentPane();
pane.setLayout(layout);


//serviceField.addActionListener(HairSalonSupport);
options.addItemListener(HairSalonSupport);
calButton.addActionListener(HairSalonSupport);
resetButton.addActionListener(HairSalonSupport);
endButton.addActionListener(HairSalonSupport);

FlowLayout flow10 = new FlowLayout();
row10.setLayout(flow10);
row10.add(amntLabel);
//row10.add(serviceField);
pane.add(row10);


GridLayout flow20 = new GridLayout(1,4,5,1);
row20.setLayout(flow20);
row20.add(optionsLabel);
row20.add(options);
row20.add(lbltype);
options.setEnabled(true);
options.addItem("Select Option");
options.addItem("Cut at $8.00");
options.addItem("Shampoo at $4.00");
options.addItem("Manicure at $18.00");
options.addItem("Style at $48.00");
options.addItem("Permanent at $18.00");
options.addItem("Trim at $6.00");
pane.add(row20);


GridLayout flow30 = new GridLayout (1,4,75,1);
row30.add(sortType);
row30.add(serviceButton);
row30.add(priceButton);
row30.add(timeButton);
pane.add(row30);

FlowLayout flow40 = new FlowLayout();
row40.setLayout(flow40);
row40.add(paymtLabel);
row40.add(paymtField);
pane.add(row40);

GridLayout flow50= new GridLayout(1,4,5,1);
row50.setLayout(flow50);
row50.add(lblservice);
row50.add(lblPrice);
row50.add(lblTime);
//row50.add(lblBalance);
pane.add(row50);      

FlowLayout flow60 = new FlowLayout();
textField.setLineWrap(true);
row60.setLayout(flow60);
JScrollPane textpane= new JScrollPane(textField,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
row60.add(textField);
pane.add(row60);

GridLayout flow70 = new GridLayout (1,4,75,1);
row70.add(calButton);
row70.add(resetButton);
row70.add(endButton);
pane.add(row70);
}

public static void main(String[] args) {
      HairSalon guiFrame= new HairSalon();
      guiFrame.setVisible(true);
      }
}
______________________________________________________________
______________________________________________________________

2nd program:

import java.awt.event.*;
import java.text.*;
import java.lang.*;
import java.io.*;
import java.awt.*;
import javax.swing.*;
import java.util.*;


public class HairSalonSupport implements      ItemListener,ActionListener
{

HairSalon gui;
double price = 0;
int minutes=0;
double term      = 0;
double intrst = 0;
double moIn      = 0;
double moTrm =      0;
double prin      = 0;
double payment      = 0;
String service[] =      {"cut","shampoo","manicure","style","permanent","trim"};
//double price[]      = { 8.00,4.00,18.00,48.00,18.00,6.00};
double price[] = {8,4,18,48,18,6};
double time[]={15,10,30,55,35,5};

int array;
int c = 1;
int index = 1;

//to format      payment prices
DecimalFormat df = new DecimalFormat("$#,###.00");

public HairSalonSupport(HairSalon      in)
{
gui=in;
}
public static void main(String []  args)
{
Arrays.sort(service);
 //Print the array
 for (int i=0; i<service.length; i++){
  System.out.println(service[i]); }

Arrays.sort(price);
 //Print the array
 for (int i=0; i<price.length; i++){
  System.out.println(price[i]); }

Arrays.sort(time);
 //Print the array
 for (int i=0; i<price.length; i++){
  System.out.println(time[i]); }
}


public void      itemStateChanged(ItemEvent      arg0)      {

      Object button = gui.options.getSelectedItem();
      String buttonPress =      button.toString();

      Object source = arg0.getSource();

   System.out.println(" == > item = " + buttonPress );

      if      (buttonPress == gui.serviceButton.getActionCommand()) {
              array =1;
              gui.textField.append("");

      }
      if      (buttonPress == gui.priceButton.getActionCommand()) {
             array = 2;
             gui.textField.append("");

             
      }
      if      (buttonPress == gui.timeButton.getActionCommand()) {
             array = 3;
             gui.textField.append("");

      }
}

public void      actionPerformed(ActionEvent event)
{
      String buttonClicked      = event.getActionCommand();
      
System.out.println(" == > action = " + buttonClicked );      
      if      (buttonClicked      ==      "Reset") {
         setNull();
   }
   if      (buttonClicked      ==      "End"){

            clearResults();
            System.exit(0);
      }
   if      (buttonClicked      =="Calculate"){
      
        
    clearResults();
    startCalculations();

    }
}

      

void reset() {

gui.paymtField.setText(null);
gui.paymtField.setText(null);
gui.textField.setText(null);

}

void end() {
System.exit(0);
}

      /*
       * Sets GUI & Declarations to Null
       */
      void setNull()  
      {
            gui.textField.setText (null);                  //Sets value to null
            gui.options.setSelectedItem("Select Option");      //Sets value to "Select Option"
            gui.paymtField.setText(null);               //Sets value to null
            index = 1;                                                      //Sets Loop-Counter to 0                          
      }
      /*
       * Sets GUI & Declarations to Null
       */
      void clearResults() //Sets GUI & Declarations to null
      {
            gui.textField.setText(null);      //Sets value to null
      }
      
      void setComboBoxNull()
      {
            gui.options.setEnabled(false);      //Disables Drop Down Menu
                                                                        
                                                                              
      }      

}

0
Comment
Question by:pgmtkl
9 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 16784839
You need to create (an) instance(s) of your main  class(es) before you can access their instance variables

http://mindprod.com/jgloss/static.html
0
 
LVL 14

Expert Comment

by:StillUnAware
ID: 16784862
As CEHJ said, You can't have both classes dependant on each other. The situation You have now is something like that:

class Num1 {
  Num2 n = new Num2();
}

class Num2 {
  Num1 n = new Num1();
}

You can try, but it's obviuos that You won't be able to compile those two, because neither of them can be instantiated without the other.
So, You must choose which class You want to be independant, then initialize it and use it as an argument in the other one. Or simply, rethink Your design.
0
 

Author Comment

by:pgmtkl
ID: 16785113
So can i move that sort to the item state changed section?
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
LVL 86

Expert Comment

by:CEHJ
ID: 16785145
>>So can i move that sort to the item state changed section?

Can't really answer that as we don't know what you want to achieve. If the starting order is not important, why don't you just declare them in a sorted way?
0
 

Author Comment

by:pgmtkl
ID: 16785626
depending on what the user selects it is supposed to sort. if they pick the sort by price it will sort the array by price. i dont think you can do that by declaring them sorted. or can you?
0
 
LVL 86

Assisted Solution

by:CEHJ
CEHJ earned 800 total points
ID: 16785752
Since these data should be together, they should be encapsulated in one class, say, a Treatment class. You could then use something similar to the following to sort a collection of Treatment:

class SimpleNodeSorter implements Comparator {

      public static final int SORT_ON_DOUBLE = 0;

      public static final int SORT_ON_CHAR = 1;

      private int sortField;

      /**
       * @param field
       */
      public SimpleNodeSorter(int sortField) {
            this.sortField = sortField;
      }

      public int compare(Object o1, Object o2) {
            SimpleNode sn1 = (SimpleNode) o1;
            SimpleNode sn2 = (SimpleNode) o2;
            switch (sortField) {
            case SORT_ON_DOUBLE:
                  double diff = sn1.getD() - sn2.getD();
                  return diff > 0.0 ? 1 : diff < 0.0 ? -1 : 0;
            default:
                  return sn1.getC() - sn2.getC();
            }
      }
}
0
 
LVL 6

Assisted Solution

by:phuocnh
phuocnh earned 400 total points
ID: 16786453
Hi pgmtkl !
Your program locates here
>>>public static void main(String []  args)
>>>{
>>>Arrays.sort(service);
 >>>//Print the array
 >>>for (int i=0; i<service.length; i++){
 >>> System.out.println(service[i]); }
You can see that main is a static method so it is a class method not object method.
service property:
>> public class HairSalonSupport implements     ItemListener,ActionListener
>> {
>> String service[] =     {"cut","shampoo","manicure","style","permanent","trim"};
is the friendly property of  HairSalonSuppor class, so it is an object property not class property.
A class method is just allowed to access class properties.
Now you can fix it as the following code:
public static void main(String []  args)
{
 HairSalonSupport support = new  HairSalonSupport( new HairSalon());
Arrays.sort(support.service);
or change  
public class HairSalonSupport implements     ItemListener,ActionListener
{
..........................................
static String service[] =     {"cut","shampoo","manicure","style","permanent","trim"};
Phuoc H. Nguyen
0
 
LVL 92

Accepted Solution

by:
objects earned 800 total points
ID: 16786591
> i dont think you can do that by declaring them sorted. or can you?

no you can't. You need to sort all three arrays according to the price or time.
To sort by time you could do something like this:

public void sortByPrice() {
    for (int i=0; i<price.length-1; i++) {
        for (int j=i+1; j<price.length; j++) {
            if (price[i] > price[j]) {
                // swap price elements
                double temp = price[i];
                price[i] = price[j];
                price[j] = temp;
                //swap time elements
                temp = time[i];
                time[i] = time[j];
                time[j] = temp;
                // swap service elements
                String name = service[i];
                service[i] = service[j];
                service[j] = name;
            }
        }
    }
}

you would have a similiar method to sort by time, which would do the same thing but compare the times instead of the price

public void sortByTime() {
   ....
   if (time[i] > time[j]) {
   ...
}


Another alternative would be to create a bean to store name, time, price

public class SalonService {
   String name;
   double price;
   double time;
   ...
}

And create seperate Comparators for each sort order

public class ByPrice implements Comparator {
   public int compare(Object o1, Object o2) {
          SalonService a = (SalonService ) o1;
          SalonService b = (SalonService ) o2;
          return (int) (a.price - b.price);
  }
}

public class ByTime implements Comparator {
   public int compare(Object o1, Object o2) {
          SalonService a = (SalonService ) o1;
          SalonService b = (SalonService ) o2;
          return (int) (a.time - b.time);
  }
}

Let me know if you have any questions.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 16792433
:-)
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
The viewer will learn how to implement Singleton Design Pattern in Java.
Suggested Courses
Course of the Month19 days, 5 hours left to enroll

834 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question