Hi,

I need a method that takes an array of Printer type and returns this array sorted by product name. What I have sorts the string names but the thing is it outputs only one product canon. I have been looking at the tutorials and have done much research but I need some guidance as to the error of my ways.

Thank you,

lynnajoe

import java.util.*;
import java.text.*;
import java.io.*;

/**
 *
 * @author Lynn
 */
public class InventoryPart2 {

    public InventoryPart2(String string) {
    }
    NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US);

    public InventoryPart2() {
    }

    public static void main(String[] args) {

        NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US);

        Printer epson = new Printer("Epson", 1, 2, 99.99);
        Printer hp = new Printer("HP", 2, 2, 149.99);
        Printer kodak = new Printer("Kodak", 3, 2, 199.99);
        Printer brother = new Printer("Brother", 4, 2, 249.99);
        Printer canon = new Printer("Canon", 5, 3, 89.99);

        String[] names = {"Epson", "HP", "Kodak", "Brother", "Canon"};
        System.out.println("The original order of the names array:\n");

        for (String productName : names) {
            System.out.println(productName);
        }
        System.out.print("\nThese are the names after being sorted:\n\n");

        Arrays.sort(names);


        for (String productName : names) {
            System.out.println(productName);
        }


        Printer[] myPrinter = new Printer[5];


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

            names[i] = myPrinter[i].getProductName();
        }

        for (int i = 0; i < 5; i++) {
            for (int j = 0; j < 5; j++) {


        System.out.printf("\nName of Product: " + Printer.getProductName()
        + "\nItem number:  " + Printer.getItemNumber() +
        "\nUnits in stock: " + Printer.getUnitsInStock()
        + "\nPrice per unit:  " + nf.format(Printer.getPricePerUnit()));
        System.out.print("\n");
        System.out.printf("\nTotal product value: " + nf.format
        (Printer.getCalculateInventory()));
        System.out.print("\n");
      }
     }
    }
   }

a quick glance, you have some big issues in there. for instance, in order for us to understand completely, you should best hand your entire code, so don't forget the Printer class.

secondly, what do you expect to achieve by doing this?

Printer[] myPrinter = new Printer[5];
for (int i = 0; i < myPrinter.length; i++) {
     names[i] = myPrinter[i].getProductName();
}

while later on, you call it the same method 'getProductName()' in a static way.

Are your methods declared static? then there's your problem, and, since you're calling your methods in a static way, I assume that this is the case.

a static variable or method has nothing to do with an instance. if you instantiate three objects of the same type, and give their INSTANCE variables (the non-static ones) different values, they will have different values. but, do the same for static values, and the first value will be overwritten by the second one, and the second one by the third one.

you call your methods by:

Printer.getProductName();

which tells me it's a static method, which can only return (wait for it ... ;) ) static variables. this variable's value depends on the class of the object, not on an instance of the class.

Hi,

Here is the printer class. This method should take in an array of type Monitor, Server or Printer and return this array sorted by the name of the product.Here is the method given as an example.

public static Printer[] sortArray (Printer myPrinters[]){}.

Then create an array of Printers; Printer myPrinters[] = new Printer[5];). Use the constructor in your class to create 5 new objects.Add the objects created in step 2 to your Array.
Call your sortArray method to sort the products in the Array.Then display them.She gave us the method to use but said we could use a different one as long as it was Printer type arrays. I tried doing an array of object but I keep running into problems no matter what I try and I have been at it for two days. At first I thought she just wanted us to sort the names but then... I have spent days on this and would appreciate being pointed in the correct direction.

Thank you,
lynnajoe

import java.util.*;
import java.text.*;

public class InventoryPart2 {

   public  InventoryPart2(String string) {

    }
NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US);


    public InventoryPart2(){

        }
    public static void main(String[] args) {

NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US);

Printer epson  = new Printer ("Epson",1,2,99.99);
Printer hp = new Printer ("HP",2,2,149.99);
Printer kodak = new Printer("Kodak",3,2,199.99);
Printer brother = new Printer ("Brother",4,2,249.99);
Printer canon   = new Printer("Canon",5,3,89.99);

String[]names = {"Epson","HP","Kodak","Brother","Canon"};
System.out.println("The original order of the names array:\n");

for (String productName : names) {
            System.out.println(productName);
        }
System.out.print("\nThese are the names after being sorted:\n\n");

Arrays.sort(names);


 for (String productName :names) {
            System.out.println(productName);
        }


       Printer[] myPrinter = new Printer[5];


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

   names[i] = myPrinter[i].getProductName();
        }

    for (int i = 0; i < 5; i++) {
        for (int j = 0; j < 5; j++) {


        System.out.printf
          ("\nName of Product: " + Printer.getProductName()
        + "\nItem number:  " + Printer.getItemNumber()+"\nUnits in stock: " +
       Printer.getUnitsInStock()+"\nPrice per unit:  " + nf.format
        (Printer.getPricePerUnit()));
    System.out.print("\n");
        System.out.printf("\nTotal product value: "+ nf.format
        (Printer.getCalculateInventory()));
System.out.print("\n");
            }
}}}







import java.util.*;
import java.text.*;
import java.io.*;

public class Printer {

    static void sort(Printer[] myPrinter) {

    }
 NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US);

     private static String productName="";
     private static int itemNumber =0;
     private static int unitsInStock=0;
     private static double pricePerUnit=0.0;


    public  Printer(String productName,int itemNumber,int unitsInStock,
            double pricePerUnit) {

            this.productName  = productName;
            this.itemNumber   = itemNumber;
            this.unitsInStock = unitsInStock;
            this.pricePerUnit = pricePerUnit;
    }
    public  String toString(){

         return     ("\nName of Product: " + Printer.getProductName()
        + "\nItem number:  " + Printer.getItemNumber() +
        "\nUnits in stock: " + Printer.getUnitsInStock()
        + "\nPrice per unit:  " + nf.format(Printer.getPricePerUnit()))+

         System.out.printf("\n")+
        System.out.printf("\nTotal product value: " + nf.format
        (Printer.getCalculateInventory()));

    }

    public static String getProductName(){
    return productName;
    }

    public static void setProductName(String productName){
        Printer.productName=productName;
    }

    public static int getItemNumber() {
        return itemNumber;
    }

    public static void setItemNumber(int itemNumber) {
        Printer.itemNumber = itemNumber;
    }

    public  NumberFormat getNf() {
        return nf;
    }

    public void setNf(NumberFormat nf) {
        this.nf = nf;
    }

    public static double getPricePerUnit() {
        return pricePerUnit;
    }

    public static void setPricePerUnit(double pricePerUnit) {
        Printer.pricePerUnit = pricePerUnit;
    }

    public static int getUnitsInStock() {
        return unitsInStock;
    }

    public static void setUnitsInStock(int unitsInStock) {
        Printer.unitsInStock = unitsInStock;
    }
    public static double getCalculateInventory(){

      double   productValue =unitsInStock*pricePerUnit;
    return productValue;
    }
}

well ... it's like I thought. your Printer contains a lot of static methods, while it shouldn't contain a single one. it also shouldn't have a sort method.

since your variables and methods are static, with every constructor, you're overwriting previous data, so you're not sorting anything anyway. all your instances are equal, for the reason I've explained in my previous post: static = bound to the class, not to an instance.

so, a few pointers:
step 1 : get rid of EVERY static keyword in your Printer class and, in your setters, replace Printer. by this. .
step 2 : remove that static void sort, you won't need it anyway.

when you've done this, you have a class with instance variables, meaning, for each instance, the info is unique and won't be overwritten by your next constructor.

if you want to sort your elements, the better approach is to implement the Comparable interface, and to implement the compareTo method.
if you've done this, the java api's contain methods that will do the sorting for you.

also, do remember: if you've done this, you can no longer call the methods in a static way in your calling method, you'll have to use the instances to print the correct data.

Hi,

These are the instructions for an assignment. I do not understand this assignment even with these instructions. I do not recall any teaching on how to populate an empty array. I am confused with this assignment and wonder if it is a little advanced for a first semester Java class. Can anyone shed light on this assignment? The first thing I learned is not to mix data types ie. Printer and String names. We are not to use collections or arrayLists or anything other than Arrays.
public static Printer[] sortArray (Printer printers[]){
Declare a String Array (i.e. names) with the same length as printers.
Declare a Printer Array (i.e. sortedPrinters) with the same length as printers.
Traverse through the printers array and place all of the Product Names into the String Array for example

for (int i = 0; i < printers.length; i++){
names[i] = printers[i].getProductName();
}

Call the sort method on the String array.
Traverse through the printers and names array. If the Product Name in the printers
array is equal to the Product Name in the names array, copy this value to the array
defined in step number 2.
You will need a nested for loop to achieve this functionality. A nested for loop consists of two loops: an outer and an inner loop. An example of a nested for loop is shown below:

for (int i = 0; i < 5; i++) { //1st loop or outer loop
 for (int j = 0; j < 5; j++ { //2nd loop or inner loop
}
}

The first loop should iterate through your printers array and the second loop should iterate through the names array;
Recall that you cannot use the = sign to compare String values;
Return the array declared in step 2 and populated in step 5.

Perhaps if someone could explain to me how to convert the Printer array but even then
the instructor wants it done with a comparison and populate an empty array. I have tried so many methods. She want us to write a method to do this. The one she gave us does not seem to work or I do not know what is missing.

Thank you,
lynnajoe

well ... I think you missed quite a bit actually. and, no, it's not that advanced, and it fits right in in a first semester class, but all beginning can be hard.

first, check which files you will be needing. Obviously, since you have to create and sort an array of Printer-objects, you'll need a Printer class. In this assignment, I only see one variable for Printer, beïng productname, so I'm going to stick with this for the moment.

write a Printer class, with just this one instance variable, a constructor (which takes this variable as a parameter) and a setter and getter for this variable. If you've done this right, you have not used the keyword static anywhere in the Printer class.

Now ... to fill your array of names:
you can assign a value to an element of an array, just like you do it for a regular object. remember:

String[] names = new String[5];
names[0] = "first Element"; // this is how you set the values for an element of
names[1] = "second Element"; // an array.

just try and implement this, then create an array of Printer objects with different productnames, create the name-array and see if you get the right values in it.

remember, don't make your variables static. You'll have to access your setter/getter through an instance of the class, not through the class itself.
for instance:

// set the value using a constructor
Printer a = new Printer("Canon"); 
// just assume your setter is named setName
a.setName("newName");
Printer b = new Printer("HP");

now, you have two instances of Printer, a and b. a contains 'newName' as value for your variable, b has 'HP' as value for the varialbe.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.