I cannot get past this error. I had taken out the dataSort method which allowed it to compile, however I need the data to sort for my assignment. When it compiled the data was not passing through my constructors, I got no data output. Any assistance is greatly appreciated . I have to add on to the program this week for class but I did not get it working correctly and can't start this weeks work without it working properly =(

Exception in thread "main" java.lang.NullPointerException
at farmersMarket.product.dataSort(product.java:147)
at farmersMarket.product.addData(product.java:137)
at farmersMarket.product.addData(product.java:120)
at farmersMarket.product.main(product.java:26)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)

package farmersMarket;

import java.text.NumberFormat;
import java.util.Formatter;
import java.util.Locale;

/**
 *
 * @author Ashey Anderson
 */
public class product {
    // Create an array 
    private static DataFormat[] Data = new DataFormat[0]; //array object
    // Keep track of current Data
    private static int currentData = 0;

    // main method begins execution of the Java application;
    public static void main(String args[]) {

        //loading the array object
        addData("Fresh Farm","Lemon",43567809, 8, 10.78);
        addData("Dale Farm","Lettuce",98561278, 6, 8.99);
        addData("Star Farm","Tomato", 37656901, 9, 12.95);
        addData("Apple Acers","Apple", 30065489, 12, 12.50);
        addData("Orangeland Farms","Orange", 67085129,1,14.99);
        
        dataSort();      

        ApplicationGUI appGUI = new ApplicationGUI(); //calls constructor

    } // end main

    public static float inventoryValue() {
        float total = 0;

        for (int x = 0; x < Data.length; x++) {
            total += Data[x].getiValue();
        }// end for loop

        return total;
    }

   // Return a string for the current item
    public static String getCurrentString() {
        if (Data.length == 0) {
            return "No data";
        } else {
            StringBuilder sb = new StringBuilder();

            // Send all output to the Appendable object sb
            Formatter formatter = new Formatter(sb, Locale.US);

            // Build Inventory String
            formatter.format(Data[currentData].toString());
            formatter.format("\n");
            formatter.format("Total Product Value: %s\n", NumberFormat.getCurrencyInstance().format(inventoryValue()));
            return sb.toString();
        }
    }

    // Method to increment current item
    public static void showNext() {
        if (currentData == Data.length - 1) {
            showFirst();
        } else {
            currentData++;
        }
    }

    // Method to go to first item
    public static void showFirst() {
        currentData = 0;
    }

    // Method to go to last item
    public static void showLast() {
        currentData = Data.length - 1;
    }

    // array of string
    public static String[] getCurrentStringArray() {
        String[] currentStringArray = new String[5];

        currentStringArray[0] = Data[currentData].getiName();
        currentStringArray[1] = Data[currentData].getDept();
        currentStringArray[2] = Integer.toString(Data[currentData].getiSku());
        currentStringArray[3] = Integer.toString(Data[currentData].getiSold());//convert items to string
        currentStringArray[4] = Double.toString(Data[currentData].getiPrice());
      
        return currentStringArray;
    }

    //assigns the Sku number to the current array object
    public static int getNextData() {
        int newCode = 0;
        for (int x = 0; x < Data.length; x++) {
            if (Data[x].getiSku() > newCode) {
                newCode = Data[x].getiSku();
            }
        }
        return newCode + 1;
    }

    public static void addData(String iName, String Dept,int iSku, int iSold, double iPrice) {
        String[] newData = new String[5]; //create a String array
        //load the array with the items that passed into the method

        
        newData[0] = iName;
        newData[1] = Dept;
        newData[2] = Integer.toString(iSku);
        newData[3] = Integer.toString(iSold);  //convert the integer pass in to a string
        newData[4] = Double.toString(iPrice);
        
        addData(newData); //method  call
        //return;

    }

    // New Method called addData
    public static void addData(String[] data) {
        // Add a new Salesman
        DataFormat iDataFormat = new DataFormat(getNextData(), data[0], data[1], Integer.valueOf(data[3]), Double.valueOf(data[4]));
        Class elementType = Data.getClass().getComponentType();
        DataFormat[] newArray = (DataFormat[]) java.lang.reflect.Array.newInstance(elementType, Data.length + 1);
        System.arraycopy(Data, 0, newArray, 0, Data.length);

        newArray[newArray.length - 1] = iDataFormat;

        Data = newArray;
        showLast();
        dataSort();
       
    }

    private static void dataSort() {
        DataFormat tmp;
        
            for (int i = 0; currentData < Data.length; currentData++){
                String s1 = Data[currentData].getiName();
                String s2 = Data[i].getiName();
                if (s1.compareTo(s2) > 0){
                    tmp = Data[currentData];
                    Data[currentData] = Data[i];
                    Data[i] = tmp;
                }
            }
        
    }
}
package farmersMarket;

/**
 *
 * @author Ashley Anderson
 */
class Data {
        
      
	private String iName;
        private String Dept;
        private int iSku;
	private double iPrice;
        private int iSold;
        
       
	public Data(int iSku, String iName, String Dept, int iSold, double iPrice) {
		
                iName = iName;
                Dept = Dept;
                iSku = iSku;
                iSold = iSold;
                iPrice = iPrice;
                
                
              
	}
	public Data(String iName){
                Dept = Dept;
                iName = iName;
                iSku = 0;
		iSold = 0;
		iPrice = 0;
               
                
              
	}

	public Data() {
                
		
		iName = "";
                Dept = "";
                iSku = 0;
		iSold = 0;
		iPrice = 0;
                
        }
    /**
     * @return the Dept
     */
        
     public String getDept(){
         return Dept;
     }
     /**
     * @param Dept the Dept to set
     */
     public void setDept(String Dept){
         this.Dept = Dept;
     }
      /**
     * @return the iSku
     */
    public int getiSku() {
        return iSku;
    }
      /**
     * @param iSku the iSku to set
     */
    public void setiSku(int iSku) {
        this.iSku = iSku;
    }

    /**
     * @return the iName
     */
    public String getiName() {
        return iName;
    }

    /**
     * @param iName the iName to set
     */
    public void setiName(String iName) {
        this.iName = iName;
    }

    /**
     * @return the iPrice
     */
    public double getiPrice() {
        return iPrice;
    }

    /**
     * @param iPrice the iPrice to set
     */
    public void setiPrice(double iPrice) {
        this.iPrice = iPrice;
    }

    /**
     * @return the iSold
     */
    public int getiSold() {
        return iSold;
    }

    /**
     * @param iSold the iSold to set
     */
    public void setiSold(int iSold) {
        this.iSold = iSold;
    }
   

    double getiValue() {
       return getiPrice()*getiSold();
    }
package farmersMarket;


import java.text.NumberFormat;
import java.util.Formatter;
import java.util.Locale;

/**
 *
 * @author esc1vbr
 */
class DataFormat extends Data{
    private String Department;
    

	public DataFormat(int iSku,String Dept, String iName, int iSold, double iPrice ){
		super (iSku, iName , Dept, iSold, iPrice );
		Department = Dept;
	}
       
    
	public DataFormat(String iName) {
		super(iName);
	}
        public String getDepartment(){
		return Department;
	}

	public void setDepartment(String dept){
		Department = dept;
	}

	public double getiValue(){
		return super.getiValue();
	}


	public double getSalesTax() {
		return super.getiValue()*.07;
	}


	public String toString() {
		StringBuilder sb = new StringBuilder();


		// Send all output to the Appendable object sb
		Formatter formatter = new Formatter(sb, Locale.US);

		// Explicit argument indices may be used to re-order output.
		
                
                formatter.format("Item Number: %d\n", getiSku());
		formatter.format("Item Name: %s\n", getiName());
		formatter.format("Farm Name: %s\n", getDept());
		formatter.format("Number of Items Sold: %d\n", getiSold());
		formatter.format("Item Price: %s\n", NumberFormat.getCurrencyInstance().format(getiPrice()));
		formatter.format("Total Sales: %s\n", NumberFormat.getCurrencyInstance().format(getiValue()));
		formatter.format("Sales Tax: %s\n", NumberFormat.getCurrencyInstance().format(getSalesTax()));
		formatter.format("Total value plus Tax: %s\n", NumberFormat.getCurrencyInstance().format(getiValue() + getSalesTax()));
		return sb.toString();
	}
}
package farmersMarket;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;

/**
 *
 * @author Ashley Anderson
 */
class ApplicationGUI implements ActionListener
{
        static JFrame jfrMain;
	// Declare 4 buttons
	static JButton jbnNext;

	// Declare a panel to draw on - holds labels
	static JPanel jplNavigation;

	// Declare Advanced panel for additional buttons - holds buttons
	static JPanel jplAdvanced;

	// Declare a text area
	static JTextArea jtxtArea;

	// Declare a Label
	static JLabel jlbLabel;

	public ApplicationGUI(){  //constructor
	    // Create and set up the window.
	    jfrMain = new JFrame("Sales Receipt");
	    jfrMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

	    // Add the text area
	    jtxtArea = new JTextArea();
	    jtxtArea.append(product.getCurrentString());
	    jfrMain.getContentPane().add(jtxtArea);

	    // Create Panel for label
	    jplNavigation = new JPanel();
            jlbLabel = new JLabel();
            jlbLabel.setText("Ander Farms");

	    // Create Advanced panel for additional buttons
	    jplAdvanced = new JPanel();

	  
	    // Create Next button
	    jbnNext = new JButton("Next");
	    jbnNext.addActionListener(this);
	    jbnNext.setActionCommand("next");

	   

	    // Add Title label to the panel
            jplNavigation.add(jlbLabel);


	    // Add buttons to Advanced Panel           
	    jplAdvanced.add(jbnNext);
	   
	    

	    

	    // Add panel to frame
	    jfrMain.getContentPane().add(jplNavigation, BorderLayout.PAGE_START);
	    jfrMain.getContentPane().add(jtxtArea, BorderLayout.WEST);
	    
	    // Add Advanced panel to frame
	    jfrMain.getContentPane().add(jplAdvanced, BorderLayout.PAGE_END);

	    //Display the window.
	    jfrMain.pack();
	    jfrMain.setVisible(true);

	}

	private static void showCurrentData(){
		jtxtArea.setText(product.getCurrentString());
	}

	

	public static void enableButtons(boolean enable) {
		jbnNext.setEnabled(enable);
		
		
		//return;
	}

	
    @Override
	public void actionPerformed(ActionEvent e) {
		// Auto-generated method stub
		if  ("next".equalsIgnoreCase(e.getActionCommand())) {
			product.showNext();
			showCurrentData();
		} 
	}

	


}

At line 139

for (int i = 0; currentData < Data.length; currentData++){

you are assigning value to "i" but then you increment "currentData" variable instead???

That is how our instructor showed us to do it and I was not fully understanding the reason behind it. I just implemented exactly how she did it with m own variables and it wont work. Is there a better way that you could show me? or a proper way I should say lol...

If I am understanding my assignment fully. I believe that string of code is to loop the current data so that we may select the next item in the array. The assignment is to create a GUI interface that allows the user to go through the items in array using a button. it needs to sort the data and display them one at a time with the ability to go to the next item.

Well if that's from your instructor, she should go back to school again... Anyway, what kind of sort algorithm are you doing here? There is certain element missing in the for loop. The "currentData" variable is one because it doesn't have its initial data.

Edit:

OK, I assume that your dataSort() is being called every time you add a new element to your data. Just change to for(int i=0; i<Data.length; i++) and see how it works.

Edited 5 Years Ago by Taywin: n/a

swapped it out and this is the result. I have found that my instruct makes quiet a few mistakes and it has made the course tedious to say the least. she is very vague and it is hard to understand how she explain things.

Exception in thread "main" java.lang.NullPointerException
at farmersMarket.product.dataSort(product.java:146)
at farmersMarket.product.addData(product.java:136)
at farmersMarket.product.addData(product.java:119)
at farmersMarket.product.main(product.java:25)
Java Result: 1

package farmersMarket;

import java.text.NumberFormat;
import java.util.Formatter;
import java.util.Locale;

/**
 *
 * @author Ashey Anderson
 */
public class product {
    // Create an array 
    private static DataFormat[] Data = new DataFormat[0]; //array object
    // Keep track of current Data
    private static int currentData = 0;

    // main method begins execution of the Java application;
    public static void main(String args[]) {

        //loading the array object
        addData("Fresh Farm","Lemon",43567809, 8, 10.78);
        addData("Dale Farm","Lettuce",98561278, 6, 8.99);
        addData("Star Farm","Tomato", 37656901, 9, 12.95);
        addData("Apple Acers","Apple", 30065489, 12, 12.50);
        addData("Orangeland Farms","Orange", 67085129,1,14.99);
        
        dataSort();      

        ApplicationGUI appGUI = new ApplicationGUI(); //calls constructor

    } // end main

    public static float inventoryValue() {
        float total = 0;

        for (int x = 0; x < Data.length; x++) {
            total += Data[x].getiValue();
        }// end for loop

        return total;
    }

   // Return a string for the current item
    public static String getCurrentString() {
        if (Data.length == 0) {
            return "No data";
        } else {
            StringBuilder sb = new StringBuilder();

            // Send all output to the Appendable object sb
            Formatter formatter = new Formatter(sb, Locale.US);

            // Build Inventory String
            formatter.format(Data[currentData].toString());
            formatter.format("\n");
            formatter.format("Total Product Value: %s\n", NumberFormat.getCurrencyInstance().format(inventoryValue()));
            return sb.toString();
        }
    }

    // Method to increment current item
    public static void showNext() {
        if (currentData == Data.length - 1) {
            showFirst();
        } else {
            currentData++;
        }
    }

    // Method to go to first item
    public static void showFirst() {
        currentData = 0;
    }

    // Method to go to last item
    public static void showLast() {
        currentData = Data.length - 1;
    }

    // array of string
    public static String[] getCurrentStringArray() {
        String[] currentStringArray = new String[5];

        currentStringArray[0] = Data[currentData].getiName();
        currentStringArray[1] = Data[currentData].getDept();
        currentStringArray[2] = Integer.toString(Data[currentData].getiSku());
        currentStringArray[3] = Integer.toString(Data[currentData].getiSold());//convert items to string
        currentStringArray[4] = Double.toString(Data[currentData].getiPrice());
      
        return currentStringArray;
    }

    //assigns the Sku number to the current array object
    public static int getNextData() {
        int newCode = 0;
        for (int x = 0; x < Data.length; x++) {
            if (Data[x].getiSku() > newCode) {
                newCode = Data[x].getiSku();
            }
        }
        return newCode + 1;
    }

    public static void addData(String iName, String Dept,int iSku, int iSold, double iPrice) {
        String[] newData = new String[5]; //create a String array
        //load the array with the items that passed into the method

        
        newData[0] = iName;
        newData[1] = Dept;
        newData[2] = Integer.toString(iSku);
        newData[3] = Integer.toString(iSold);  //convert the integer pass in to a string
        newData[4] = Double.toString(iPrice);
        
        addData(newData); //method  call
        //return;

    }

    // New Method called addData
    public static void addData(String[] data) {
        // Add a new Salesman
        DataFormat iDataFormat = new DataFormat(getNextData(), data[0], data[1], Integer.valueOf(data[3]), Double.valueOf(data[4]));
        Class elementType = Data.getClass().getComponentType();
        DataFormat[] newArray = (DataFormat[]) java.lang.reflect.Array.newInstance(elementType, Data.length + 1);
        System.arraycopy(Data, 0, newArray, 0, Data.length);

        newArray[newArray.length - 1] = iDataFormat;

        Data = newArray;
        showLast();
        dataSort();
       
    }

    private static void dataSort() {
        DataFormat tmp;
        
            for (int i=0; i<Data.length; i++){
                String s1 = Data[currentData].getiName();
                String s2 = Data[i].getiName();
                if (s1.compareTo(s2) > 0){
                    tmp = Data[currentData];
                    Data[currentData] = Data[i];
                    Data[i] = tmp;
                }
            }
        
    }
}

Edited 5 Years Ago by Blink383: n/a

Errr... Where did she graduate from... Don't go to that school!!! Is this an IT class? Is it called like "Introduction to Java Programming" or something? I have seen very similar example like this from an IT instructor before...

Anyway, the code contains so many hard-coded which is very difficult to deal with. So could you please tell me what sort algorithm are you going for? It is the only thing I need here. Currently, it is plainly wrong.

Edited 5 Years Ago by Taywin: n/a

It is IT-215 Java Programming, at University of Phoenix. She is older and I have found some of the instructions to be out-dated. This is the last class for my associates degree. They seem to keep the curriculum the same and reuse it over and over, I have found post dating back to 2004 or earlier, with the same assignments from people trying to get help. The main problem is that it is 100% online and if the teacher isn't putting forth the effort to explain of provide feedback the students get really lost. I have been looking into ITT tech or possible a traditional campus for my bachelors but at the moment this is the best way for me to go to school and juggle life with kids. OK back on track! And thanks again for your time :)

if this is not what you meant I apologies, I am still pretty new (*Cough--obviously*

1) create a GUI that displays the name, department, sku, number sold, and price.

2) It is then to calculate the the number sold by the price of item to get the total price.

3) Then needs to take the total price and multiple tax (.07) to get the total order value.

4) The data should sort into alphabetical order.

5) The output should display each item one at a time with a next button to go through the items.

Edited 5 Years Ago by Blink383: n/a

OK, now it is clear. You can use any sort algorithm to sort it. You can choose any sort algorithm you like from http://en.wikipedia.org/wiki/Sorting_algorithm [Wikipedia]. An easy algorithm to understand and implement could be Bubble sort.

/*
pseudo code from Wikipedia
procedure bubbleSort( A : list of sortable items )
   n = length(A)
   repeat
      swapped = false
      for i = 1 to n-1 inclusive do

         end if
      end for
      n = n - 1
   until not swapped
end procedure
*/

Do you understand the pseudo code? You just need to replace your current dataSort() to match the pseudo code. Remember, "A" is your "Data" and "for i = 1 to n-1 inclusive do" means "for(int i=1; i<n; i++)". Hmm... And the "repeat-until" is similar to "do-while" loop. Oh and the "swap" is what you did in your code line 143~145. If you aren't successful, please get back.

Edited 5 Years Ago by Taywin: n/a

Ah yes, we worked on the bubble sort. Thank you so much I will implement this now and update you if it works or not :)

here is what I got. My if statement is giving me an error.

bad operand types for binary operator '<'
first type: farmersMarket.DataFormat
second type: farmersMarket.DataFormat

private static void dataSort() {
        DataFormat tmp;
        boolean swapped = true;
        int n = 0;
            while (swapped){
                    swapped = false; 
                    n++;
                    for (int i = 0; i < Data.length - n; i++){
                    if (Data[i] < Data[i+1]){
                        tmp = Data[i];
                        Data[i+1] = tmp;
                        swapped = true;
                    }
                    }
                    
        }

OK, I will compare the pseudo code with your current code. But before that, the error you got is from comparing object with object which is incorrect. If you look back to your original code line 140~141, that is the way you compare the object with object in this case. An object of DataFormat calls getiName() method to retrieve the data's String name. Then compare two names using compareTo() String method. If the return value is negative, the caller string has lower order in natural order (ascending order). If it is equal to 0, both strings are the same. If the return value is positive, the caller string has higher order in natural order (ascending order).

private static void dataSort() { // procedure bubbleSort( A : list of sortable items )
  DataFormat tmp;  // you need it later, so it is fine to declare here
  boolean swapped = true;  // good, you know how to deal with it.
  // int n = 0;  <-- the pseudo code initiates with the array A length, not 0
  int n = Data.length;  // n = length(A)
  while (swapped) {   // repeat
    swapped = false
    // for (int i=0; i<Data.length-n; i++)  <-- incorrect, we need n from above
    for (int i=1; i<n; i++) {  // this is where  for i = 1 to n-1 inclusive do
      // use i=1 so i-1 will stay in the array bound & up to n-1
      if (Data[i-1].getiName().compareTo(Data[i].getiName())>0) {  // if A[i-1] > A[i]
        tmp = Data[i-1];
        Data[i-1] = Data[i];   // your code misses this line, be careful!
        Data[i] = tmp;
      }  // end if
    }  // end for loop
    n--;  // n = n - 1
  }  // end while or until not swapped
}

PS: Your code builds up "Data" variable from an array which is not supposed to be used dynamically (keep dumping the existing array and recreate a new one). Please do not learn the way to build up array from your assignment.

Edited 5 Years Ago by Taywin: n/a

Still get an error -

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at farmersMarket.product.dataSort(product.java:147)
at farmersMarket.product.addData(product.java:136)
at farmersMarket.product.addData(product.java:119)
at farmersMarket.product.main(product.java:25)
Java Result: 1

private static void dataSort() {
        DataFormat tmp;
        boolean swapped = true;
        int n = Data.length;
            while (swapped){
                    swapped = false; 
                    for (int i = 0; i < n; i++){
                    if (Data[i-1].getiName().compareTo(Data[i].getiName())>0){
                        tmp = Data[i-1];
                        Data[i-1] = Data[i];
                        Data[i] = tmp;
                        swapped = true;
                    }  //END IF
                    }  //END FOR
                    
                    n--;
                    
        }
    }

I think i fix it but I still get null pointer exception error. I am so annoyed with the class. the Teacher gave us 3 hour notice before the live tutorial and I did not get to make it because she posted tutorial time at 1:30 pst and held it at 5 pst, which happens to be the only time during the day that I can't be at the computer (I leave the house at 1 everyday and dont get back online until after 6)....... how lame is that!!!

I have also realized that I have two methods meant to do different things named the same. The addData methods... one is meant to pass the array info and the other is to add new item (I think) however I can't seem to logically make sense of that part... wouldn't I only need one to pull the info from the array? (wish I could have made the tutorial ;)


here is my current error message and the code for the product document.

run:
Exception in thread "main" java.lang.NullPointerException
at farmersMarket.product.dataSort(product.java:147)
at farmersMarket.product.addData(product.java:136)
at farmersMarket.product.addNewData(product.java:119)
at farmersMarket.product.main(product.java:26)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)

package farmersMarket;

import java.text.NumberFormat;
import java.util.Formatter;
import java.util.Locale;

/**
 *
 * @author Ashey Anderson
 */
public class product {
    // Create an array 
    private static DataFormat[] Data = new DataFormat[0]; //array object
    // Keep track of current Data
    private static int currentData = 0;

    // main method begins execution of the Java application;
    public static void main(String args[]) {

        //loading the array object
        addNewData("Fresh Farm","Lemon",43567809, 8, 10.78);
        addNewData("Dale Farm","Lettuce",98561278, 6, 8.99);
        addNewData("Star Farm","Tomato", 37656901, 9, 12.95);
        addNewData("Apple Acers","Apple", 30065489, 12, 12.50);
        addNewData("Orangeland Farms","Orange", 67085129,1,14.99);
        
        dataSort();      

        ApplicationGUI appGUI = new ApplicationGUI(); //calls constructor

    } // end main

    public static float inventoryValue() {
        float total = 0;

        for (int x = 0; x < Data.length; x++) {
            total += Data[x].getiValue();
        }// end for loop

        return total;
    }

   // Return a string for the current item
    public static String getCurrentString() {
        if (Data.length == 0) {
            return "No data";
        } else {
            StringBuilder sb = new StringBuilder();

            // Send all output to the Appendable object sb
            Formatter formatter = new Formatter(sb, Locale.US);

            // Build Inventory String
            formatter.format(Data[currentData].toString());
            formatter.format("\n");
            formatter.format("Total Product Value: %s\n", NumberFormat.getCurrencyInstance().format(inventoryValue()));
            return sb.toString();
        }
    }

    // Method to increment current item
    public static void showNext() {
        if (currentData == Data.length - 1) {
            showFirst();
        } else {
            currentData++;
        }
    }

    // Method to go to first item
    public static void showFirst() {
        currentData = 0;
    }

    // Method to go to last item
    public static void showLast() {
        currentData = Data.length - 1;
    }

    // array of string
    public static String[] getCurrentStringArray() {
        String[] currentStringArray = new String[5];

        currentStringArray[0] = Data[currentData].getiName();
        currentStringArray[1] = Data[currentData].getDept();
        currentStringArray[2] = Integer.toString(Data[currentData].getiSku());
        currentStringArray[3] = Integer.toString(Data[currentData].getiSold());//convert items to string
        currentStringArray[4] = Double.toString(Data[currentData].getiPrice());
      
        return currentStringArray;
    }

    //assigns the Sku number to the current array object
    public static int getNextData() {
        int newCode = 0;
        for (int x = 0; x < Data.length; x++) {
            if (Data[x].getiSku() > newCode) {
                newCode = Data[x].getiSku();
            }
        }
        return newCode + 1;
    }

    public static void addNewData(String iName, String Dept,int iSku, int iSold, double iPrice) {
        String[] newData = new String[5]; //create a String array
        //load the array with the items that passed into the method

        
        newData[0] = iName;
        newData[1] = Dept;
        newData[2] = Integer.toString(iSku);
        newData[3] = Integer.toString(iSold);  //convert the integer pass in to a string
        newData[4] = Double.toString(iPrice);
        
        addData(newData); //method  call
        //return;

    }

    // New Method called addData
    public static void addData(String[] data) {
        // Add a new item
        DataFormat iDataFormat = new DataFormat(getNextData(), data[0], data[1], Integer.valueOf(data[3]), Double.valueOf(data[4]));
        Class elementType = Data.getClass().getComponentType();
        DataFormat[] newArray = (DataFormat[]) java.lang.reflect.Array.newInstance(elementType, Data.length + 1);
        System.arraycopy(Data, 0, newArray, 0, Data.length);

        newArray[newArray.length - 1] = iDataFormat;

        Data = newArray;
        showLast();
        dataSort();
       
    }

     private static void dataSort() {
        DataFormat tmp;
        boolean swapped = true;
        int n = Data.length;
            while (swapped){
                    swapped = false; 
                    for (int i = 1; i < n; i++){
                    if (Data[i-1].getiName().compareTo(Data[i].getiName())>0){
                        tmp = Data[i-1];
                        Data[i-1] = Data[i];
                        Data[i] = tmp;
                        swapped = true;
                    }  //END IF
                    }  //END FOR
                    
                    n--;
                    
        }
    }
}

Thank once again for all your help
Exception in thread "main" java.lang.NullPointerException
at farmersMarket.product.dataSort(product.java:147)
at farmersMarket.product.addData(product.java:136)
at farmersMarket.product.addNewData(product.java:119)
at farmersMarket.product.main(product.java:26)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)

package farmersMarket;

import java.text.NumberFormat;
import java.util.Formatter;
import java.util.Locale;

/**
 *
 * @author Ashey Anderson
 */
public class product {
    // Create an array 
    private static DataFormat[] Data = new DataFormat[0]; //array object
    // Keep track of current Data
    private static int currentData = 0;

    // main method begins execution of the Java application;
    public static void main(String args[]) {

        //loading the array object
        addNewData("Fresh Farm","Lemon",43567809, 8, 10.78);
        addNewData("Dale Farm","Lettuce",98561278, 6, 8.99);
        addNewData("Star Farm","Tomato", 37656901, 9, 12.95);
        addNewData("Apple Acers","Apple", 30065489, 12, 12.50);
        addNewData("Orangeland Farms","Orange", 67085129,1,14.99);
        
        dataSort();      

        ApplicationGUI appGUI = new ApplicationGUI(); //calls constructor

    } // end main

    public static float inventoryValue() {
        float total = 0;

        for (int x = 0; x < Data.length; x++) {
            total += Data[x].getiValue();
        }// end for loop

        return total;
    }

   // Return a string for the current item
    public static String getCurrentString() {
        if (Data.length == 0) {
            return "No data";
        } else {
            StringBuilder sb = new StringBuilder();

            // Send all output to the Appendable object sb
            Formatter formatter = new Formatter(sb, Locale.US);

            // Build Inventory String
            formatter.format(Data[currentData].toString());
            formatter.format("\n");
            formatter.format("Total Product Value: %s\n", NumberFormat.getCurrencyInstance().format(inventoryValue()));
            return sb.toString();
        }
    }

    // Method to increment current item
    public static void showNext() {
        if (currentData == Data.length - 1) {
            showFirst();
        } else {
            currentData++;
        }
    }

    // Method to go to first item
    public static void showFirst() {
        currentData = 0;
    }

    // Method to go to last item
    public static void showLast() {
        currentData = Data.length - 1;
    }

    // array of string
    public static String[] getCurrentStringArray() {
        String[] currentStringArray = new String[5];

        currentStringArray[0] = Data[currentData].getiName();
        currentStringArray[1] = Data[currentData].getDept();
        currentStringArray[2] = Integer.toString(Data[currentData].getiSku());
        currentStringArray[3] = Integer.toString(Data[currentData].getiSold());//convert items to string
        currentStringArray[4] = Double.toString(Data[currentData].getiPrice());
      
        return currentStringArray;
    }

    //assigns the Sku number to the current array object
    public static int getNextData() {
        int newCode = 0;
        for (int x = 0; x < Data.length; x++) {
            if (Data[x].getiSku() > newCode) {
                newCode = Data[x].getiSku();
            }
        }
        return newCode + 1;
    }

    public static void addData(String iName, String Dept,int iSku, int iSold, double iPrice) {
        String[] newData = new String[5]; //create a String array
        //load the array with the items that passed into the method

        
        newData[0] = iName;
        newData[1] = Dept;
        newData[2] = Integer.toString(iSku);
        newData[3] = Integer.toString(iSold);  //convert the integer pass in to a string
        newData[4] = Double.toString(iPrice);
        
        addData(newData); //method  call
        //return;

    }

    // New Method called addData
    public static void addData(String[] data) {
        // Add a new Salesman
        DataFormat iDataFormat = new DataFormat(getNextData(), data[0], data[1], Integer.valueOf(data[3]), Double.valueOf(data[4]));
        Class elementType = Data.getClass().getComponentType();
        DataFormat[] newArray = (DataFormat[]) java.lang.reflect.Array.newInstance(elementType, Data.length + 1);
        System.arraycopy(Data, 0, newArray, 0, Data.length);

        newArray[newArray.length - 1] = iDataFormat;

        Data = newArray;
        showLast();
        dataSort();
       
    }

     private static void dataSort() {
        DataFormat tmp;
        boolean swapped = true;
        int n = Data.length;
            while (swapped){
                    swapped = false; 
                    for (int i = 1; i < n; i++){
                    if (Data[i-1].getiName().compareTo(Data[i].getiName())>0){
                        tmp = Data[i-1];
                        Data[i-1] = Data[i];
                        Data[i] = tmp;
                        swapped = true;
                    }  //END IF
                    }  //END FOR
                    
                    n--;
                    
        }
    }
}

I have implemented it by implementing my own DataFormat class using what I see. The sorting part works. Now the problem is actually from how you build the DataFormat as it is now really inefficient and buggy. Look at the code below... I did it by modifying your code from [] array to ArrayList and use it with my own DataFormat class. Now, the problem is no longer the sorting part, but other part of your code. May have to look at it again. I cannot do it right now because I will be busy until tomorrow evening... :(

// Your main code...
import java.text.NumberFormat;
import java.util.Formatter;
import java.util.Locale;
import java.util.ArrayList;

/**
 *
 * @author Ashey Anderson
 */
public class product {
  // Create an array 
  private static ArrayList<DataFormat> Data = new ArrayList<DataFormat>();
  // Keep track of current Data
  private static int currentData = 0;

  // main method begins execution of the Java application;
  public static void main(String args[]) {

    //loading the array object
    addNewData("Fresh Farm","Lemon",43567809, 8, 10.78);
    addNewData("Dale Farm","Lettuce",98561278, 6, 8.99);
    addNewData("Star Farm","Tomato", 37656901, 9, 12.95);
    addNewData("Apple Acers","Apple", 30065489, 12, 12.50);
    addNewData("Orangeland Farms","Orange", 67085129,1,14.99);
    
    dataSort();
    for (int i=0; i<Data.size(); i++) {
      System.out.println(Data.get(i));
    }

//    ApplicationGUI appGUI = new ApplicationGUI(); //calls constructor

  } // end main

  public static float inventoryValue() {
    float total = 0;

    for (int x = 0; x < Data.size(); x++) {
      total += Data.get(x).getiValue();
    }// end for loop

    return total;
  }

  // Return a string for the current item
  public static String getCurrentString() {
    if (Data.size() == 0) {
      return "No data";
    } else {
      StringBuilder sb = new StringBuilder();

      // Send all output to the Appendable object sb
      Formatter formatter = new Formatter(sb, Locale.US);

      // Build Inventory String
      formatter.format(Data.get(currentData).toString());
      formatter.format("\n");
      formatter.format("Total Product Value: %s\n", NumberFormat.getCurrencyInstance().format(inventoryValue()));
      return sb.toString();
    }
  }

  // Method to increment current item
  public static void showNext() {
    if (currentData == (Data.size()-1)) {
      showFirst();
    } else {
      currentData++;
    }
  }

  // Method to go to first item
  public static void showFirst() {
    currentData = 0;
  }

  // Method to go to last item
  public static void showLast() {
    currentData = Data.size() - 1;
  }

  // array of string
  public static String[] getCurrentStringArray() {
    String[] currentStringArray = new String[5];

    currentStringArray[0] = Data.get(currentData).getiName();
    currentStringArray[1] = Data.get(currentData).getDept();
    currentStringArray[2] = Integer.toString(Data.get(currentData).getiSku());
    currentStringArray[3] = Integer.toString(Data.get(currentData).getiSold());//convert items to string
    currentStringArray[4] = Double.toString(Data.get(currentData).getiPrice());
   
    return currentStringArray;
  }

  //assigns the Sku number to the current array object
  public static int getNextData() {
    int newCode = 0;
    for (int x = 0; x < Data.size(); x++) {
      if (Data.get(x).getiSku() > newCode) {
        newCode = Data.get(x).getiSku();
      }
    }
    return newCode + 1;
  }

  public static void addNewData(String iName, String Dept, int iSku, int iSold, double iPrice) {
    String[] newData = new String[5]; //create a String array
    //load the array with the items that passed into the method

    
    newData[0] = iName;
    newData[1] = Dept;
    newData[2] = Integer.toString(iSku);
    newData[3] = Integer.toString(iSold); //convert the integer pass in to a string
    newData[4] = Double.toString(iPrice);
    
    addData(newData); //method call
    //return;

  }

  // New Method called addData
  public static void addData(String[] data) {
    // Add a new item
    int newCode = getNextData();
    Data.add(new DataFormat(newCode, data));
    showLast();
    dataSort();
    
  }

   private static void dataSort() {
    DataFormat tmp1, tmp2;
    boolean swapped = true;
    int n = Data.size();
      while (swapped){
          swapped = false; 
          for (int i = 1; i < n; i++){
          if (Data.get(i-1).getiName().compareTo(Data.get(i).getiName())>0){
            tmp1 = Data.get(i-1);
            tmp2 = Data.get(i);
            Data.remove(i);
            Data.add(i, tmp1);
            Data.remove(i-1);
            Data.add(i-1, tmp2);
            swapped = true;
          } //END IF
      } //END FOR
      n--;
    }
  }
}

This is a simple DataFormat class I implemented.

class DataFormat {
  String name;
  String department;
  int sku;
  int sold;
  float price;

  public DataFormat(int code, String[] dat) {
    name = dat[0];
    department = dat[1];
    sku = code;
    sold = Integer.parseInt(dat[3]);
    price = Float.parseFloat(dat[4]);
  }


  public float getiValue() {
    return (price*sold);
  }


  public float getiPrice() {
    return price;
  }


  public int getiSold() {
    return sold;
  }


  public String getiName() {
    return name;
  }


  public int getiSku() {
    return sku;
  }


  public String getDept() {
    return department;
  }


  @Override
  public String toString() {
    String out = "";
    out += "Item Name: "+name+"\n";
    out += "Department: "+department+"\n";
    out += "SKU: "+sku+"\n";
    out += "Sold: "+sold+"\n";
    out += "Price: $"+price+"\n";
    return out;
  }
}

So I tried the code you corrected and it works but it's passing some of the information wrong. instead of passing all 8 digits through the sku it is only displaying one digit. The department and the item name are crossed and it is not totaling each item's order only the total overall. I am going to mess with it and see where I get. I will post if I get stuck. THANK YOU SOOOOOO MUCH!

Ok, so I implemented the code you fixed up and added the other elements I needed into the program. Problems I'm having are that my total, tax, nd overall sales are not calculating. I am guessing it has something to do with them not going through the construct or them not interlinking with the rest of the array information.

The other issue that I am having is finding where the code is reading the sku wrong. It should display an 8 digit number for the sku but it is only passing one digit back with the output. I have looked it over and I believe it has to do with getNextData method being incorrect. I did mess with it some but did not get it to work.

If you don't mind looking it over and seeing if you can spot the issue, once again I thank all help, it is greatly appreciated.

import java.text.NumberFormat;
import java.util.Formatter;
import java.util.Locale;
import java.util.ArrayList;

/**
 *
 * @author Ashey Anderson
 */
public class product {
  // Create an array 
  private static ArrayList<DataFormat> Data = new ArrayList<DataFormat>();
  // Keep track of current Data
  private static int currentData = 0;

  // main method begins execution of the Java application;
  public static void main(String args[]) {

    //loading the array object
    addNewData("Fresh Farm","Lemon", 43567809, 8, 10.78);
    addNewData("Dale Farm","Lettuce", 98561278, 6, 8.99);
    addNewData("Star Farm","Tomato", 37656901, 9, 12.95);
    addNewData("Apple Acers","Apple", 30065489, 12, 12.55);
    addNewData("Orangeland Farms","Orange", 67085129, 1, 14.99);
    
    dataSort();
    for (int i=0; i<Data.size(); i++) {
      System.out.println(Data.get(i));
    }

   ApplicationGUI appGUI = new ApplicationGUI(); //calls constructor

  } // end main
//Method for calculating total inventory
  public static float inventoryValue() {
    float total = 0;
    for (int x = 0; x < Data.size(); x++) {
      total += Data.get(x).getTotal();
    }// end for loop

    return total;
  }

  // Return a string for the current item
  public static String getCurrentString() {
    if (Data.isEmpty()) {
      return "No data";
    } else {
      StringBuilder sb = new StringBuilder();

      // Send all output to the Appendable object sb
      Formatter formatter = new Formatter(sb, Locale.US);

      // Build Inventory String
      formatter.format(Data.get(currentData).toString());
      formatter.format("\n");
      formatter.format("Total Product Value: %s\n", NumberFormat.getCurrencyInstance().format(inventoryValue()));
      return sb.toString();
    }
  }

  // Method to increment current item
  public static void showNext() {
    if (currentData == (Data.size()-1)) {
      showFirst();
    } else {
      currentData++;
    }
  }

  // Method to go to first item
  public static void showFirst() {
    currentData = 0;
  }

  // Method to go to last item
  public static void showLast() {
    currentData = Data.size() - 1;
  }

  // array of string
  public static String[] getCurrentStringArray() {
    String[] currentStringArray = new String[5];

    currentStringArray[0] = Data.get(currentData).getiName();
    currentStringArray[1] = Data.get(currentData).getDept();
    currentStringArray[2] = Integer.toString(Data.get(currentData).getiSku());
    currentStringArray[3] = Integer.toString(Data.get(currentData).getiSold());//convert items to string
    currentStringArray[4] = Double.toString(Data.get(currentData).getiPrice());
   
    return currentStringArray;
  }

  //assigns the Sku number to the current array object
  public static int getNextData() {
    int newCode = 0;
    for (int x = 0; x < Data.size(); x++) {
      if (Data.get(x).getiSku() > newCode) {
        newCode = Data.get(x).getiSku();
      }
    }
    return newCode + 1;
  }

  public static void addNewData(String iName, String Dept, int iSku, int iSold, double iPrice) {
    String[] newData = new String[5]; //create a String array
    //load the array with the items that passed into the method

    
    newData[0] = iName;
    newData[1] = Dept;
    newData[2] = Integer.toString(iSku);
    newData[3] = Integer.toString(iSold); //convert the integer pass in to a string
    newData[4] = Double.toString(iPrice);
    
    addData(newData); //method call
    //return;

  }

  // New Method called addData
  public static void addData(String[] data) {
    // Add a new item
    int newCode = getNextData();
    Data.add(new DataFormat(newCode, data));
    showLast();
    dataSort();
    
  }

   private static void dataSort() {
    DataFormat tmp1, tmp2;
    boolean swapped = true;
    int n = Data.size();
      while (swapped){
          swapped = false; 
          for (int i = 1; i < n; i++){
          if (Data.get(i-1).getiName().compareTo(Data.get(i).getiName())>0){
            tmp1 = Data.get(i-1);
            tmp2 = Data.get(i);
            Data.remove(i);
            Data.add(i, tmp1);
            Data.remove(i-1);
            Data.add(i-1, tmp2);
            swapped = true;
          } //END IF
      } //END FOR
      n--;
    }
  }
}
package farmersMarket;

class DataFormat {
  String name;
  String department;
  int sku;
  int sold;
  float price;
  double Total;
  double Tax;
  double OverallTotal;

  public DataFormat(int code, String[] dat) {
    name = dat[1];
    department = dat[0];
    sku = code;
    sold = Integer.parseInt(dat[3]);
    price = Float.parseFloat(dat[4]);
  }


  public float getTotal() {
    return (price*sold);
  }
  
  public double getTax(){
    return (Total * .07);
  }
  public double getOverallTotal(){
    return (Total+Tax);
  }

  public float getiPrice() {
    return price;
  }


  public int getiSold() {
    return sold;
  }


  public String getiName() {
    return name;
  }


  public int getiSku() {
    return sku;
  }


  public String getDept() {
    return department;
  }


  @Override
  public String toString() {
    String out = "";
    out += "Item Name: "+name+"\n";
    out += "Department: "+department+"\n";
    out += "SKU: "+sku+"\n";
    out += "Sold: "+sold+"\n";
    out += "Price: $"+price+"\n";
    out += "Total: $"+Total+"\n";
    out += "Tax: $"+Tax+"\n";
    out+= "Overall Total: $"+OverallTotal+"\n";
    
    return out;
  }
}

Generally, the SKU number is not display as 8 digit because the value is in integer. When it is converted to string in the toString(), it has not changed its format. You need to create the display format yourself.

In your case, the implementation does NOT really read the incoming SKU but reassign it (from your original code) to ensure the uniqueness. You will need to make a decision either accept the number entered by user or generate a new number or both?

Also, variable "Total," "Tax," and "OverallTotal" are not needed in this case. You could actually return the value called from other methods in there. The toString() will call methods instead of a variable.

// i.e.
  public float getTotal() {
    return (price*sold);
  }
  
  public double getTax(){
    return (getTotal()*0.7);
  }

  public double getOverallTotal(){
    return (getTotal()+getTax());
  }

// and when call in toString() would be like...
  out += "Total: $"+getTotal()+"\n";

Now you will face value with too long decimal number (such as 12.99999998). There are couple ways to solve this in order to display the number correctly with 2 decimal. An easy way to do is to use "DecimalFormat" class to do the format for you. Declare it as your class's variable, and you can use it anywhere.

import java.text.DecimalFormat;  // need this to include the class

class DataFormat {
  ...
  ...
  final DecimalFormat CFORMAT = new DecimalFormat("#.##");  // want it to be constant

  // then use it anywhere you want as... for example...
  @Override
  public String toString() {
    ...
    ...
    out += "Total: $"+CFORMAT.format(getTotal())+"\n";
    ...
  }
}

You would see that you need to pass in the problem float to the format() method of the CFORMAT which is the DecimalFormat object. It will automatically return a string which is the 2 decimal places of the number. Unfortunately, you can't do the same with SKU number. You need to implement it yourself by converting it to Integer if the number is less than 8 digits.

For the variables total,tax, and overallTotal, when I coded the methods for them netbeans keep highlighting them stating I needed to declare the variables. Is this just because it thinks it needs them? Also, is the reason they are reading 0 for the output because I declared them as variables instead of using parameters from other methods in the program?

For the variables total,tax, and overallTotal, when I coded the methods for them netbeans keep highlighting them stating I needed to declare the variables. Is this just because it thinks it needs them? Also, is the reason they are reading 0 for the output because I declared them as variables instead of using parameters from other methods in the program?


Forgot about the decimal format. I added that in but when I tried to add the code in with the toString method for the output. I keep getting errors stating it was an illegal start of the argument. would this be the correct format to display the formatter. I did import the java.util packages and I did initialize it for use.

formatter.format (out += "Price: ",NumberFormat.getCurrencyInstance().format(price));

Edited 5 Years Ago by Blink383: Forgot information

If you want to keep Total and Tax, then you need to compute it right inside the constructor. Also, you need to make them all private because they aren't supposed to be changed from the outside. If you declare primitive (int, long, float, and double) and not intialize them, their value will be 0. That's why you need to calculate them after you declare as the class's variables.

For the NumberFormat, it is not in "util" package but in "text" package. You need to use import java.text.NumberFormat;

Here is the link to Java 6 API documentation http://download.oracle.com/javase/6/docs/api/

Edited 5 Years Ago by Taywin: n/a

So far so good I got the total, tax, and overall working. Now I just need to format it to display currency not decimal (this is one of the requirements for the assignment) or would it be both? doesn't the currency formatter display the output with two decimals?

And still need to work on the sku but I figure I'll get everything else in order first.

Thanks again :D

I can't get the formatter to work the right way. I have tried with the decimal formatter and the currency one, I have both initializers included still. I have tried it several ways this is the most accurate output I have received so far. I either get an error when you run it or I get strange out put like such:


Item Name: Tomato
Department: Star Farm
SKU: 3
Sold: 9
Price: $12.95
Total: $116.549995
Tax: $116.549995
81.58499679565429
Overall Total: $116.549995
81.58499679565429
198.13499221801757

Total Product Value: $422.32

this output came from the below code

public String toString() {
    Formatter cformat = new Formatter(Locale.US); 
    final DecimalFormat CFORMAT = new DecimalFormat("0.00");
      
    String out = "";
    out += "Item Name: "+name+"\n";
    out += "Department: "+department+"\n";
    out += "SKU: "+sku+"\n";
    out += "Sold: "+sold+"\n";
    out += "Price: $"+price+"\n";
    out += "Total: $"+ cformat.format(getTotal()+"\n");
    out += "Tax: $"+ cformat.format(getTax()+"\n");
    out+= "Overall Total: $"+ cformat.format(getOverallTotal()+"\n");
    
    return out;
  }
}

Edited 5 Years Ago by Blink383: n/a

Change the final DecimalFormat CFORMAT = new DecimalFormat("0.00"); to final DecimalFormat CFORMAT = new DecimalFormat("#.##"); because they are different. Also, why do you have cformat? You could use only CFORMAT without a Formatter.

Edited 5 Years Ago by Taywin: n/a

technically I am suppose to use the currency formatter and not the decimal. I tried both to see which was working. I was unsure which to use really.

Any number formatting class should work because they extends from NumberFormat class. However,you should use the NumberFormat class. Remember that the class is in "text" not "util" but the format is still the same ("#.##"). :)

By the way, have you decided about SKU yet? Do you want the class to automatically generate for you or you will let users enter it?

Edited 5 Years Ago by Taywin: n/a

it needs to get it generate from the array list of sku's. I have the number formating class coded in right now and i get this error.

Exception in thread "main" java.lang.IllegalArgumentException: Cannot format given Object as a Number
at java.text.DecimalFormat.format(DecimalFormat.java:505)
at java.text.Format.format(Format.java:157)
at farmersMarket.DataFormat.toString(DataFormat.java:77)
at java.lang.String.valueOf(String.java:2902)
at java.io.PrintStream.println(PrintStream.java:821)
at farmersMarket.product.main(product.java:35)
Java Result: 1

package farmersMarket;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Formatter;
import java.util.Locale;

class DataFormat {
  String name;
  String department;
  int sku;
  int sold;
  float price;
  
  public DataFormat(int code, String[] dat) {
    name = dat[1];
    department = dat[0];
    sku = code;
    sold = Integer.parseInt(dat[3]);
    price = Float.parseFloat(dat[4]);
  }


 private float getTotal() {
    return (price*sold);
  }
  
  private double getTax(){
    return (getTotal()*0.7);
  }

  private double getOverallTotal(){
    return (getTotal()+getTax());
  }

  public float getiPrice() {
    return price;
  }


  public int getiSold() {
    return sold;
  }


  public String getiName() {
    return name;
  }


  public int getiSku() {
    return sku;
  }


  public String getDept() {
    return department;
  }


  @Override
  public String toString() {
     
    final DecimalFormat CFORMAT = new DecimalFormat("#.##");
      
    String out = "";
    out += "Item Name: "+name+"\n";
    out += "Department: "+department+"\n";
    out += "SKU: "+sku+"\n";
    out += "Sold: "+sold+"\n";
    out += "Price: $"+price+"\n";
    out += "Total: $"+ CFORMAT.format(getTotal()+"\n");
    out += "Tax: $"+ CFORMAT.format(getTax()+"\n");
    out+= "Overall Total: $"+ CFORMAT.format(getOverallTotal()+"\n");
    
    return out;
  }
}
import java.text.NumberFormat;
import java.util.Formatter;
import java.util.Locale;
import java.util.ArrayList;

/**
 *
 * @author Ashey Anderson
 */
public class product {
  // Create an array 
  private static ArrayList<DataFormat> Data = new ArrayList<DataFormat>();
  // Keep track of current Data
  private static int currentData = 0;

  // main method begins execution of the Java application;
  public static void main(String args[]) {

    //loading the array object
    addNewData("Fresh Farm","Lemon", 43567809, 8, 10.78);
    addNewData("Dale Farm","Lettuce", 98561278, 6, 8.99);
    addNewData("Star Farm","Tomato", 37656901, 9, 12.95);
    addNewData("Apple Acers","Apple", 30065489, 12, 12.55);
    addNewData("Orangeland Farms","Orange", 67085129, 1, 14.99);
    
    dataSort();
    for (int i=0; i<Data.size(); i++) {
      System.out.println(Data.get(i));
    }

   ApplicationGUI appGUI = new ApplicationGUI(); //calls constructor

  } // end main
//Method for calculating total inventory
  public static float inventoryValue() {
    float total = 0;
    for (int x = 0; x < Data.size(); x++) {
      total += Data.get(x).sku;
    }// end for loop

    return total;
  }

  // Return a string for the current item
  public static String getCurrentString() {
    if (Data.isEmpty()) {
      return "No data";
    } else {
      StringBuilder sb = new StringBuilder();

      
      
      
      
      
      
      // Send all output to the Appendable object sb
      Formatter formatter = new Formatter(sb, Locale.US);

      // Build Inventory String
      formatter.format(Data.get(currentData).toString());
      formatter.format("\n");
      formatter.format("Total Product Value: %s\n", NumberFormat.getCurrencyInstance().format(inventoryValue()));
      return sb.toString();
    }
  }

  // Method to increment current item
  public static void showNext() {
    if (currentData == (Data.size()-1)) {
      showFirst();
    } else {
      currentData++;
    }
  }

  // Method to go to first item
  public static void showFirst() {
    currentData = 0;
  }

  // Method to go to last item
  public static void showLast() {
    currentData = Data.size() - 1;
  }

  // array of string
  public static String[] getCurrentStringArray() {
    String[] currentStringArray = new String[5];

    currentStringArray[0] = Data.get(currentData).getiName();
    currentStringArray[1] = Data.get(currentData).getDept();
    currentStringArray[2] = Integer.toString(Data.get(currentData).getiSku());
    currentStringArray[3] = Integer.toString(Data.get(currentData).getiSold());//convert items to string
    currentStringArray[4] = Double.toString(Data.get(currentData).getiPrice());
   
    return currentStringArray;
  }

  //assigns the Sku number to the current array object
  public static int getNextData() {
    int newCode = 0;
    for (int x = 0; x < Data.size(); x++) {
      if (Data.get(x).getiSku() > newCode) {
        newCode = Data.get(x).getiSku();
      }
    }
    return newCode + 1;
  }

  public static void addNewData(String iName, String Dept, int iSku, int iSold, double iPrice) {
    String[] newData = new String[5]; //create a String array
    //load the array with the items that passed into the method

    
    newData[0] = iName;
    newData[1] = Dept;
    newData[2] = Integer.toString(iSku);
    newData[3] = Integer.toString(iSold); //convert the integer pass in to a string
    newData[4] = Double.toString(iPrice);
    
    addData(newData); //method call
    //return;

  }

  // New Method called addData
  public static void addData(String[] data) {
    // Add a new item
    int newCode = getNextData();
    Data.add(new DataFormat(newCode, data));
    showLast();
    dataSort();
    
  }

   private static void dataSort() {
    DataFormat tmp1, tmp2;
    boolean swapped = true;
    int n = Data.size();
      while (swapped){
          swapped = false; 
          for (int i = 1; i < n; i++){
          if (Data.get(i-1).getiName().compareTo(Data.get(i).getiName())>0){
            tmp1 = Data.get(i-1);
            tmp2 = Data.get(i);
            Data.remove(i);
            Data.add(i, tmp1);
            Data.remove(i-1);
            Data.add(i-1, tmp2);
            swapped = true;
          } //END IF
      } //END FOR
      n--;
    }
  }

Edited 5 Years Ago by Blink383: n/a

You need those getTax(), getTotal(), and getOverall... methods to be public, not private. Also you should move final DecimalFormat CFORMAT = new DecimalFormat("#.##"); line to be your class's variable, not method variable.

I think you are confused about private and public I talked earlier. If you are going to keep those as variables declared in the class, you should put them as private; otherwise, their values can be easily updated from external call. But if you just want to return the computed value via variable, they should be public because you normally cannot modify the method's definition from the outside.

Edit
Oh and... You formatted it wrong.
=> CFORMAT.format(getTotal()+"\n"); // wrong
=> CFORMAT.format(getTotal()) + "\n"; // correct

Edited 5 Years Ago by Taywin: n/a

This article has been dead for over six months. Start a new discussion instead.