How do I make an array from usr input?

Well... I am trying and trying and all I do fails... I am trying to make an array from user input data.

I am building a constructor for product class... it has item name, item price, stock qty, total price... the thing is that I want to make a program to create the items and pass them to an array that will have the itemname as its name. so I can lateron call itemname[0] and that would be = to its price... for example.

I am making this program for a gui-less template. So it shouldnt be so hard to accomplish... but I started roughly 4 weeks ago making some progress in here with java so i dont know much.

Any aid will be apreciated.

[661 byte] By [Elvenelfa] at [2007-11-27 9:17:09]
# 1

Don't pass the constructor's parameters as an array, pass them individually. When you take the user input, store each piece in a temp variable until you have them all entered. Then pass them all to the constructor.

I'm guessing that's what you're trying to do, why don't you post what you have so far so we can be sure.

Message was edited by:

hunter9000

hunter9000a at 2007-7-12 22:07:24 > top of Java-index,Java Essentials,Java Programming...
# 2

Is it possible to make the array inside the constructor!?

I have this so far... the rest is on its way tho... I am coding as I read in here for replies to the question. ;)

public class product

{

private String ItemName;

private int ItemID;

private double ItemPrice;

private int ItemStock;

private double TotalInvent;

/** Creates a new instance of product */

public product()

{

setItemName(ItemName);

setItemID(ItemID);

setItemPrice(ItemPrice);

setItemStock(ItemStock);

}

public String getItemName(){

return ItemName;

}

public void setItemName(String ItemName){

this.ItemName = ItemName;

}

public int getItemID(){

return ItemID;

}

public void setItemID(int ItemID){

this.ItemID = ItemID;

}

public double getItemPrice(){

return ItemPrice;

}

public void setItemPrice(double ItemPrice){

this.ItemPrice = ItemPrice;

}

public int getItemStock(){

return ItemStock;

}

public void setItemStock(int ItemStock){

this.ItemStock = ItemStock;

}

}

Elvenelfa at 2007-7-12 22:07:24 > top of Java-index,Java Essentials,Java Programming...
# 3

Are you trying to make an array or Product objects? If so, then you do that outside the Product class. Something like this:

Product[] products = new Product[<however many you want>];

loop {

read input

create single Products

add the newly created Product to the next position in the array

}

hunter9000a at 2007-7-12 22:07:24 > top of Java-index,Java Essentials,Java Programming...
# 4

so it would be a multidimensional array? I can only make one array per data type right? I cant have an array with numbers in it (like double or Int)?

If this is the case, I would need an array of names, and an array of every other thing (property) i get for my products so I can then call each array[0] to get each value for the same item... lol this is getting confusing... i knew arrays would do mashed potatoes outta my brains lol ...

ok... so more or less like that... I can then do the arrays in the main class right at the end of the loop for user input .

Elvenelfa at 2007-7-12 22:07:24 > top of Java-index,Java Essentials,Java Programming...
# 5
Slow down! I can imagine that you only need an array of Product, unless youwant to read all the input before creating any Product objects -- buy why wouldyou want to it that way -- awkward!
BigDaddyLoveHandlesa at 2007-7-12 22:07:24 > top of Java-index,Java Essentials,Java Programming...
# 6

Well...I also need to get the total amount (cash value) of my inventory... if I entered X amount of items, each item will have its itemid, its price and its stock amount or qty. so I will have to calc each items total invent value to sum them all up.

I need a way to separate each item. so I thought making an array of each little thing would help me keep things kinda tidy... wouldnt that be right!? or I could do this some other way!?

Elvenelfa at 2007-7-12 22:07:24 > top of Java-index,Java Essentials,Java Programming...
# 7

> Well...I also need to get the total amount (cash

> value) of my inventory... if I entered X amount of

> items, each item will have its itemid, its price and

> its stock amount or qty. so I will have to calc each

> items total invent value to sum them all up.

>

> I need a way to separate each item. so I thought

> making an array of each little thing would help me

> keep things kinda tidy... wouldnt that be right!? or

> I could do this some other way!?

Nope! You're fighting against object orientation instead of using it. Each Product object maintains the info for a single Product. If you want to know the total value of a certain Product, then you ask it by calling the getTotalValue() method (or whatever you want to call it). That Product calculates that value and returns it (itemPrice * itemStock right?). Then you can just loop over each Product in the array, and add up the totals from each one.

hunter9000a at 2007-7-12 22:07:24 > top of Java-index,Java Essentials,Java Programming...
# 8

> Nope! You're fighting against object orientation

> instead of using it. Each Product object maintains

> the info for a single Product. If you want to know

> the total value of a certain Product, then you ask it

> by calling the getTotalValue() method (or whatever

> you want to call it). That Product calculates that

> value and returns it (itemPrice * itemStock right?).

> Then you can just loop over each Product in the

> array, and add up the totals from each one.

That is exactly what I thought.... I more or less had done something like that... but I had it inside the constructor...

public double getTotalValue(){

return ItemStock * ItemPrice;

}

I am not sure how I will end up doing this lol But this is sure getting interesting. I am starting to get ideas here. When I have more of my main class completed I will post it here for review... I am sure it will have some fixing to do, so I will try to come back with no compiling errors if possible ;) Thanks a lot for your posts guys.

Elvenelfa at 2007-7-12 22:07:24 > top of Java-index,Java Essentials,Java Programming...
# 9

> public class product

> {

>private String ItemName;

>private int ItemID;

>private double ItemPrice;

>private int ItemStock;

>private double TotalInvent;

>

>public product()

>{

> setItemName(ItemName);

> setItemID(ItemID);

> setItemPrice(ItemPrice);

> setItemStock(ItemStock);

>}

>

Is it just me, or does anyone else see something seriously wrong with this constructor?

To the OP: How does one pass information to the constructor to tell it how to fill the instance variables?

petes1234a at 2007-7-12 22:07:24 > top of Java-index,Java Essentials,Java Programming...
# 10
> Is it just me, or does anyone else see something seriously wrong with this constructor?Woops, I didn't see that, it was so obvious?
BigDaddyLoveHandlesa at 2007-7-12 22:07:24 > top of Java-index,Java Essentials,Java Programming...
# 11

> > > public class product

> > {

> >private String ItemName;

> >private int ItemID;

> >private double ItemPrice;

> >private int ItemStock;

> >private double TotalInvent;

> >

> >public product()

> >{

> > setItemName(ItemName);

> > setItemID(ItemID);

> > setItemPrice(ItemPrice);

> > setItemStock(ItemStock);

> >}

> >

>

> Is it just me, or does anyone else see something

> seriously wrong with this constructor?

>

> To the OP: How does one pass information to the

> constructor to tell it how to fill the instance

> variables?

I used this exact same constructor for another program and it worked perfectly as it is. I use the scanner to get user input in the main class and that worked ok... i dont know how that could be seriously wrong with the constructor or whatever. I only recently started to use java, and if the goal instead of helping me is to toss faults to my face in a rather rude way... well i can always try to get kind aid at another forum, but for some obscure reason the forums from the developers of the darn language itself were at the top of my list. Thanks for pointing something out... without even saying exactly what it is... i now have bigger doubts about my code... thanks for nothing petes1234.......

Elvenelfa at 2007-7-12 22:07:24 > top of Java-index,Java Essentials,Java Programming...
# 12
Well, i'm sure it wasent ment to make you cry;)And I got to say this is the best javaforum I have been on. Quick and good help.. So dont give up hope just yet ;)
kongsberga at 2007-7-12 22:07:24 > top of Java-index,Java Essentials,Java Programming...
# 13

> I used this exact same constructor for another

> program and it worked perfectly as it is. I use the

> scanner to get user input in the main class and that

> worked ok... i dont know how that could be

> seriously wrong with the constructor or

> whatever. I only recently started to use java, and if

> the goal instead of helping me is to toss faults to

> my face in a rather rude way... well i can always try

> to get kind aid at another forum, but for some

> obscure reason the forums from the developers of the

> darn language itself were at the top of my list.

Actually, Sun only hosts this forum; the people who answer here a just a bunch of developers, students, etc. who like to help, learn, or whatever.

> Thanks for pointing something out... without even

> saying exactly what it is... i now have bigger doubts

> about my code... thanks for nothing petes1234.......

petes1234's point was that you do not pass values into your constructor but you set them none-the-less.

The more standard idiom is something like this (except for capitalization):

public class product {

private String ItemName;

private int ItemID;

private double ItemPrice;

private int ItemStock;

private double TotalInvent;

public product(String ItemName, int ItemID, double ItemPrice, int ItemStock, double TotalInvent) {

setIte mName(ItemName);

setItemID(ItemID);

setItemPrice(ItemPrice);

setItemStock(ItemStock);

}

}

Message was edited by:

jbish

jbisha at 2007-7-12 22:07:24 > top of Java-index,Java Essentials,Java Programming...
# 14

> I used this exact same constructor ...

> ... i dont know how that could be

> seriously wrong with the constructor or

> whatever....

> if the goal instead of helping me is to toss

> faults to my face in a rather rude way...

> Thanks for pointing something out... without even

> saying exactly what it is... i now have bigger doubts

> about my code... thanks for nothing petes1234.......

To the OP, the point of this forum in my mind and in many others is to help you to help yourself. You have to stretch your mind to learn. That occasionally means that we will give you partial information and let you try to figure the rest out for yourself. Honestly, I was trying to be helpful. If you could figure out what the solution is to your constructor problem, great. You have benefited. If you can't, then you think, ask questions about it, and we can try to nudge you a little further in the direction of the answer. Trust me, if you can figure it out for yourself, then you own the solution. It will be burned in your brain forever. If you have taken offense to what I said, well I'm sorry. It was not meant to insult you, but to instruct you. If you don't agree with this, well so be it.

Another thing to consider: Even if an answer here doesn't appear to solve your problem, even if it should totally miss the point -- the best thing to do to motivate others (all volunteers, mind you) to continue trying to help you is by showing respect and gratitude for the investment of time that was put into dealing with your issue.

The rest is up to you. Good luck.

/Pete

petes1234a at 2007-7-12 22:07:24 > top of Java-index,Java Essentials,Java Programming...
# 15

Well, I'm done with this... I could not make it compile for nothing that I would do... thanks to all who posted trying to help me out.

It might be too soon for me to start with java... I managed to do this in php in no time... but java... good lord... why must it be so difficult to get around them errors... I ended up in total frustration as nothing I tried worked out. I couldnt make it stick. the worst part is that i dont even understand why... bah... anyways, in the end I settled to go to sleep having this scrap of code that is worth less than a penny:

public class Product {

private String Name[]; // product name

private double Sku[]; // sku number

private double Qty[]; //quantity in stock

private double Price[]; // price per product

private double Value[]; // item inventory value

public Product(String Name,double Sku,double Qty,double Price) {// argument constructor

setName(Name);

setSku(Sku);

setQty(Qty);

setPrice(Price);

} // end five-argument constructor

// set item name

public void setName( String[] Name ) {

this.Name = Name;

} // end method setName

// return item name

public String[] getName() {

return Name;

} // end method getName

// set item sku

public void setSku( double[] Sku ) {

this.Sku = Sku;

} // end method setSku

// return item sku

public double[] getSku() {

return Sku;

} // end method getSku

// set item Qty

public void setQty( double[] Qty ) {

this.Qty = Qty;

} // end method setQty

// return item Qty

public double[] getQty() {

return Qty;

} // end method getQty

// set item Price

public void setPrice( double[] Price ) {

this.Price = Price;

} // end method setPrice

// return item price

public double[] getPrice() {

return Price;

} // end method getPrice

// calculate inventory value

public double getValue() {

return Qty * Price;

} // end method inventory value

// return String representation of item object

public String toString() {

return String.format( "%s: %s\n%s: %s\n%s: %s\n%s: %.2f",

"Name", Name,

"Sku", Sku,

"Instock", Qty,

"Price", Price,

"Total Item Value", Value);

} //end method toString

} // end class Product

and the main class:

public class Main {

/** Creates a new instance of Main */

public Main() {

}

/**

* @param args the command line arguments

*/

public static void main(String[] args) {

String Name="";

double Sku=0.0;

double Qty=0.0;

double Price=0.0;

double Value=0.0;

Product product = new Product(Name,Sku,Qty,Price);

Scanner input = new Scanner(System.in);//create new scanner to read user input from command window

String iName[] = { "Pencil", "Pen", "Eraser", "Marker", "Paper", "Highlighter" }; // array of item names

double iSku[] = { 8003, 8007, 8005, 8009, 8008, 8007 }; // array of sku numbers

double iQty[] = { 29, 38, 12, 27, 405, 21 }; // array of quantities in stock

double iPrice[] = { 1.50, 1.50, 0.75, 1.50, 0.15, 1.25 }; // array of price per item

double iValue[] = { iQty[0] * iPrice[0], iQty[1] * iPrice[1],

iQty[2] * iPrice[2], iQty[3] * iPrice[3], iQty[4] * iPrice[4], iQty[5]

* iPrice[5] }; // array of total value per item

System.out.println("Enter Item Name");

Name = input.nextLine();

if (Name.equals(iName[0])){

product.getSku()=iSku[0];

product.setQty()=iQty[0];

product.setPrice()=iPrice[0];

Value=iValue[0];

System.out.print(product.toString());

}

}

}

And now that I kinda vented... I want to apologize for my behavior earlier. I am grumpy due to lack of sleep. I have been trying too hard to make this thing... but no worries... i ended up doing it in php... no more java for a while... (till tomorrow :p )

Message was edited by:

Elvenelf

Elvenelfa at 2007-7-21 22:58:17 > top of Java-index,Java Essentials,Java Programming...
# 16

> It might be too soon for me to start with java...

> I managed to do this in php in no time...

> but java... good lord...

Exactly what I would say if I tried to implement something like this in php.

> public class Product {

>private String Name[]; // product name

>private double Sku[]; // sku number

>private double Qty[]; //quantity in stock

>private double Price[]; // price per product

>private double Value[]; // item inventory value

I don't think you want to make these values arrays. Keep them single values like this:

public class Product {

private String Name;

private int Sku; // change to int or string

private int Qty; //change to int. 0.5 quantity makes no sense.

private double Price;

private double Value;

Since I kind of feel bad about our misunderstanding, I'm giving you here more than I should be doing (shame), but just this once:

You'll probably make an array out of Product objects, but don't do it with these instance variables here. In fact, from first look, you probably want to get rid of all array references in this class (all of these "[]"). You keep your Product nice and simple and then when you want to use this class, you make an array of the class's objects.

Something like this:

class FooStuff

public class FooStuff {

private String label;

private int idNumber;

private int quantumNumber;

private double frequency;

private double calcField;

public FooStuff(String label,int idNumber,int quantumNumber,double frequency)

{

this.label = label;

this.idNumber = idNumber;

this.quantumNumber = quantumNumber;

this.frequency = frequency;

}

public String getLabel()

{

return this.label;

}

public double getCalcField() {

return quantumNumber / frequency;

}

public String toString() {

return String.format( "Label: %s\n" +

"ID Number: %s\n" +

"Period: %s\n" +

"Frequency: %.2f \n" +

"Period / Frequency: %.2f",

label, idNumber, quantumNumber, frequency, getCalcField());

}

}

class PlayWithFooStuff

import java.util.Scanner;

public class PlayWithFooStuff

{

private FooStuff[] myFoos =

{

new FooStuff("foo1", 456, 4, 2.2),

new FooStuff("foo2", 448, 5, 2.3),

new FooStuff("foo3", 487, 6, 2.75),

new FooStuff("foo4", 111, 7, 2.50),

new FooStuff("foo5", 555, 8, 2.15),

new FooStuff("foo6", 979, 9, 2.25)

};

private Scanner scan;

public PlayWithFooStuff()

{

}

private void getAndCheckInput()

{

scan = new Scanner(System.in);

String myLabel = "";

//loop to get input and display til user types "quit"

while (!myLabel.equalsIgnoreCase("quit") && !myLabel.equalsIgnoreCase("exit"))

{

System.out.print("Enter Label (quit to exit): ");

myLabel = scan.nextLine();

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

{

if (myLabel.equalsIgnoreCase(myFoos[i].getLabel()))

{

System.out.print(myFoos[i].toString());

System.out.println();

System.out.println();

}

}

}

}

public static void main(String[] args)

{

PlayWithFooStuff myMain = new PlayWithFooStuff();

myMain.getAndCheckInput();

}

}

Message was edited by:

petes1234

petes1234a at 2007-7-21 22:58:17 > top of Java-index,Java Essentials,Java Programming...
# 17
Thanks for this... I really see now the amount of wrong things I had in there... no wonder it wouldnt compile rewrite after rewrite... the whole idea of what I was doing was completely wrong... I need a java for dummies book asap! lol
Elvenelfa at 2007-7-21 22:58:17 > top of Java-index,Java Essentials,Java Programming...
# 18

I made some more changes to this little program.... Please comment the code below:

/*

* Main.java

*

* Created on June 26, 2007, 4:21 PM

*

* To change this template, choose Tools | Template Manager

* and open the template in the editor.

*/

package inventoryprogram;

import java.util.*;

import java.awt.*;

/**

*

* @author jlmorales

*/

public class Main {

/** Creates a new instance of Main */

public Main() {

}

private Product[] myProducts ={//create inventory array of items for use with product constructor

new Product("Pencils",6,312,0.15),

new Product("Pens",7,233,1.00),

new Product("Markers",8,112,1.76),

new Product("Highlighter",9,324,1.95),

new Product("Eraser",10,127,0.10),

new Product("Tacks",11,309,1.00)

};

private Scanner input;//bring scanner up

private void getTotalValue(){//get the total inventory value

double Tval = 0.0;

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

Tval = Tval + myProducts[i].getValue();

}

System.out.printf("Total Inventory Value: $%.2f", Tval);

}//end getTotalValue method

private void Asort(){

String[] Nname = new String[6];

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

Nname[i] = myProducts[i].getName();

}

Arrays.sort(Nname);

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

System.out.println(Nname[i]);

}

}

private void getInput() {//get user input to display item information when match within array and user input is found

//initialize variables

String Name = "";

int Sku = 0;

int Qty = 0;

double Price = 0.0;

input = new Scanner(System.in);//initialize scanner

Main myMain = new Main();//initialize main class to call a method from within

//loop to get input until quit or exit is entered

while(!Name.equalsIgnoreCase("quit") && !Name.equalsIgnoreCase("exit")) {

myMain.Asort();

//int num=1;

//

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

//

//System.out.printf("%d) %s\n", num, myProducts[i].getName());

//num++;

//}

System.out.println("Enter an Item Name from the list (quit to exit):");//ask for item name

Name=input.nextLine();//get user input

for(int i=0;i<myProducts.length;i++)//loop around array length

{

if (Name.equalsIgnoreCase(myProducts[i].getName()))//if match is found from user input and array items...

{

System.out.print(myProducts[i].toString()+"\n");//execute the toString method from Product class

System.out.printf("Total Item Value: $%.2f\n", myProducts[i].getValue());//execute getValue method from Product class

myMain.getTotalValue();

//print two empty (blank) lines

System.out.println();

System.out.println();

}

}

}

}

/**

* @param args the command line arguments

*/

public static void main(String[] args) {

Main myMain = new Main();//initialize main class to call a method from within

myMain.getInput();//call to getInput method which is where the action goes on...

}

}

Also this , even though I did not modify this after the changes I made in the main.java....

/*

* Product.java

*

* Created on June 26, 2007, 10:47 PM

*

* To change this template, choose Tools | Template Manager

* and open the template in the editor.

*/

package inventoryprogram;

/**

*

* @author JL Morales

*/

public class Product {

private String Name; // product name

private int Sku; // sku number

private int Qty; //quantity in stock

private double Price; // price per product

private double Value; // item inventory value

public Product(String Name,int Sku,int Qty,double Price) {// argument constructor

this.Name = Name;

this.Sku=Sku;

this.Qty=Qty;

this.Price=Price;

} // end four-argument constructor

// return item name

public String getName() {

return this.Name;

} // end method getName

// calculate item value

public double getValue() {

return Value = this.Price * this.Qty;

} // end method item value

// return String representation of item object

public String toString() {

return String.format( "%s: %s\n%s: %d\n%s: %d\n%s: %.2f",

"Name", Name,

"Sku", Sku,

"Qty", Qty,

"Price", Price);

} //end method toString

} // end class Product

I'd really like some comments... I wanted to sort the array... is the way I used ok? Is there a way to sort the array of myProducts[#]? Is the method used to get the total inventory value good enough? It does its job well but is it efficient!? Could it be better!?

Thanks in advance for any feedback.>

Elvenelfa at 2007-7-21 22:58:17 > top of Java-index,Java Essentials,Java Programming...
# 19

Two comments:

Try to learn the Java coding conventions. The first letter of class names should be capitalized. Objects and other variables should begin with lower case letters.

In Product, I'd get rid of the Value variable. Your program calculates this fine, so why not leave it at that:

public double getValue()

{

//return Value = this.Price * this.Qty;

return this.Price * this.Qty;

}

Of course if the class has another internal use for a value variable, then leave it in, but right now, I don't see one.

petes1234a at 2007-7-21 22:58:17 > top of Java-index,Java Essentials,Java Programming...
# 20

Thanks,

See here:

for(int i=0;i<myProducts.length;i++)//loop around array length

{

if (Name.equalsIgnoreCase(myProducts[i].getName()))//if match is found from user input and array items...

{

System.out.print(myProducts[i].toString()+"\n");//execute the toString method from Product class

System.out.printf("Total Item Value: $%.2f\n", myProducts[i].getValue());//execute getValue method from Product class

myMain.getTotalValue();

//print two empty (blank) lines

System.out.println();

System.out.println();

}

I am using getValue for individual items total price, and then the method inside main for the total inventory value as a global amount (all items).>

Elvenelfa at 2007-7-21 22:58:17 > top of Java-index,Java Essentials,Java Programming...
# 21

> Thanks,

>

> See here:

I saw that, but that is not inside the Product class. All the outside classes see is the getValue which is and should be a calculated value. If you delete the variable (and change the getValue to remove the Value = part), your program will still run.

Also as to sorting, check out the Comparator interface. This is what you need:

http://java.sun.com/j2se/1.5.0/docs/api/java/util/Comparator.html

This will help you to sort the array easily and cleanly. Also, don't be overwhelmed by this. It will be easy to implement this. Once you create your comparator, then sort it with Arrays.sort(myProducts, productComparator); and it's sorted. What you have right now doesn't sort the myProduct array, but rather a another array that you have created. This is no good. Also, it would break down if the number of items in the myProducts array changes.

Message was edited by:

petes1234

Message was edited by:

petes1234

petes1234a at 2007-7-21 22:58:17 > top of Java-index,Java Essentials,Java Programming...
# 22

> This will help you to sort the array easily and

> cleanly. Also, don't be overwhelmed by this. It

> will be easy to implement this. Once you create your

> comparator, then sort it with Arrays.sort(myProducts,

> productComparator); and it's sorted. What you have

> right now doesn't sort the myProduct array, but

> rather a another array that you have created. This

> is no good. Also, it would break down if the number

> of items in the myProducts array changes.

I see... you are right... in my trials i had the Nname number wrong and it would not compile. Once I set it to 6 then it compiled. I could change the number and use myProducts.length instead perhaps? That would give correct values?

Elvenelfa at 2007-7-21 22:58:17 > top of Java-index,Java Essentials,Java Programming...