1

I'm having problems on how and where to put arrays. I figured out how and where to put a loop so it will keep on gathering multiple user data that will be stored inside the arrays but I don't know where to put arrays. There will be an array for product numbers, an array for product name, and an array for price.

import java.io.*; 
public class DataInsideArrays 
{ 
public static DataInputStream a = new     DataInputStream(System.in) 
public static void main(String      args[])throws Exception 
{ 
int y = 0; 
for(int x=1;x<=100;x++)
{                           
System.out.println("1 - Maintenance");
System.out.println("2 - Transaction");
System.out.println("");
System.out.print("Enter code: ");
int code =
Integer.parseInt(a.readLine()); 
System.out.println("");
if(code==l) 
{ 
System.out.print("") ; 
System.out.print("Product number: ");
System.out.print("Product name: "); 
String prodname = a.readLine(); 
System.out.print("Price: "); 
int price = Integer.parseInt(a.readLine()); 
System.out.println(""); 
} 
else if(code==2) 
{
System.out.println("Display List of           Products-Prices") 
System.out.print("Enter product number:
") ; 
int prodnum
Integer.parseInt(a.readLine()); 
System.out.println("")
} 
if(code==3) 
{ 
System.out.println("Invalid");        
System.out.println("Restart");
System.out.println(""); 
}}}}
10
  • please tag question to appropriate/relevant one's. Looks like its java question, but you have tagged it to javascript. Commented Sep 18, 2014 at 13:38
  • @ManjunathDR oops sorry. Changed it right away. Thanks.
    – Axiom_CC
    Commented Sep 18, 2014 at 13:44
  • Did you OCR the code? I got a lot of syntax errors.
    – Narmer
    Commented Sep 18, 2014 at 13:54
  • 1
    question is not clear..what u want to do?
    – kirti
    Commented Sep 18, 2014 at 13:59
  • @Narmer oh sorry I'll check the codes. Btw I used Jcreator there.
    – Axiom_CC
    Commented Sep 18, 2014 at 14:00

5 Answers 5

0

First of all, where do you get this l (lowercase L) value in your for loop? Shouldn't this be 1 (number one)? Furthermore, it would be even better if it is 0 (zero) so you can use it as an index for your array.

Second thing, what's the point of int y = 0'? You are not using y anywhere in your program.

int y = 0;
for(int x = l; x <= 100; x++)

Change it to:

for(int x = 0; x < 100; x++)

Since you want to have 3 separate arrays, you should have 3 separate indexes to keep track of them.

Now let's see how to initialize an array to store the data. You should declare the size as a variable at the top of your class (or locally in your main()) to make it easier to change it later across your program. You can do the same with your array. Declare it inside your class or locally inside the main(). I will show you how to declare both outside of the class, but you should try it the other way too for practice.

Now remember, when using arrays you have to know the size of the array in advance as soon as you create it and you cannot change that size after. This means only that many elements can fit inside the array. If you want variable size structures, check out some of the answers with ArrayLists.

public class DataInsideArrays 
{ 
    public static DataInputStream a = new DataInputStream(System.in) 
    public static int size = 100; // now you only change this number and everything works
    public static int[] productNumbers = new int[size];
    public static String[] productNames = new String[size];
    public static int[] productPrices = new int[size];

    public static void main(String args[]) throws Exception 
    { 

        int prodnumIndex = 0; // index for tracking product numbers
        int prodnameIndex = 0; // index for tracking product names
        int prodpriceIndex = 0; // index for tracking product prices
        for(int x = 0; x < size; x++)
        {        
        // ... your code...

        // ...

        int prodNum = Integer.parseInt(a.readLine());
        // check if we didn't reach our maximum size
        if(prodnumIndex < productNumbers.length) {
            productNumbers [prodnumIndex] = prodnum;
            prodnumIndex++; // increment
        } else {
            System.out.println("Cannot add product number. Reached maximum amount.");
        }


        // ...

        String prodName = a.readLine();
        // check if we didn't reach our maximum size
        if(prodnameIndex < productNames.length) {
            productNames [prodnameIndex] = prodName ;
            prodnameIndex++; // increment
        } else {
            System.out.println("Cannot add product name. Reached maximum amount.");
        }

        // ...

        int prodPrice = Integer.parseInt(a.readLine());
        // check if we didn't reach our maximum size
        if(prodpriceIndex < productPrices.length) {
            productPrices [prodpriceIndex] = prodPrice ;
            prodpriceIndex++; // increment
        } else {
            System.out.println("Cannot add product number. Reached maximum amount.");
        }   

        // ... 

        }            

Another way you can achieve this is to create an object called Product that will contain the properties you need and then have an array of that object.

class Product {
    int num;
    String name;
    int price;
    Product(int num, String name, int price) {
        this.num = num;
        this.name = name;
        this.price = price;
    }
}

// ...

// declare your array of `Product` objects...
Product[] products = new Product[size];

// ...

// then you can do something like
System.out.println("Enter product number:");
int prodNum = Integer.parseInt(a.readLine());
System.out.println("Enter product name:");
String prodName = a.readLine();
System.out.println("Enter product price:");
int prodPrice = Integer.parseInt(a.readLine());

products[INDEX] = new Product(prodNum, prodName, prodPrice);

// ...

Also, consider using a double of a float for the product price since it is more realistic representation of actual products.

2
  • Sorry I didn't recognized the lowercase l. Change it. So just like that? I would add 2 more arrays for product names and product prices. The other one is for product number.
    – Axiom_CC
    Commented Sep 18, 2014 at 14:58
  • The 1st long one could do the trick. I'll run this and see what's still missing. Thanks!
    – Axiom_CC
    Commented Sep 18, 2014 at 15:08
0

Do you have to use an array and "if" statements? Common practice is to use a List as switch statement:

int[] productArray = new int[100];
List<Integer> productList = new ArrayList<Integer>();
for(int x=1;x<=100;x++) {
    switch (code){
    case 1:
        productArray[x-1] = Integer.parseInt(a.readLine());
        productList.add(new Integer(a.readLine()) );
        break;
    default: 
        System.out.println("Invalid")
        break;
    }
}
3
  • Well I don't know. I have experience on using switch but wouldn't it make my scenario a lot more complicated?
    – Axiom_CC
    Commented Sep 18, 2014 at 14:23
  • @Axiom_CC switch would make it much easier for you. Every time you would have a lot of options and want to put a lot of if statements, you should use a switch instead. It makes the code cleaner and execution is faster.
    – nem035
    Commented Sep 18, 2014 at 14:30
  • Thanks. I'll change the codes and see if it works with other things in my mind.
    – Axiom_CC
    Commented Sep 18, 2014 at 14:34
0

You should use a List instead of an array, because you don't know a priori the length for them.

A List allows you to dinamically add an element as soon as you got it, so you should "put the array" under the user input.

List<String> names = new ArrayList<String>(); //<-- do the same for price(Integer) and product number (Integer)
public static void main(String args[]) throws Exception) { 
//...
    if(code==1) //<-- This was a l, check again your code.
    { 
        System.out.print("") ; 
        System.out.print("Product number: ");
        System.out.print("Product name: "); 
        String prodname = a.readLine(); 

        names.add(prodname); //<-- add value to ArrayList

        System.out.print("Price: "); 
        int price = Integer.parselnt(a.readLine()); 
        System.out.println(""); 
    }
//...
}

To print the array content you just need to iterate over the ArrayList:

for(String prodname: names)
    System.out.println(prodname); //<-- This will print all your product names
7
  • If I use lists instead of arrays, will I be able to display the data which I added? In case when the user choosed 2nd code
    – Axiom_CC
    Commented Sep 18, 2014 at 14:20
  • See my edit. You can print the content iterating over the list.
    – Narmer
    Commented Sep 18, 2014 at 14:23
  • Yeah but how can I display just one data. Like if I entered "2 in product number" then the 2nd data will be displayed only.
    – Axiom_CC
    Commented Sep 18, 2014 at 14:32
  • There is no correlation between the three arrays. Neither if you use a list or an array, in the way you tought this out the three arrays are completely independant. What you need is a Map or better yet create your own Product class.
    – Narmer
    Commented Sep 18, 2014 at 14:36
  • I'm reading about the Map and I don't think I get it. It's alot more complicated I think.
    – Axiom_CC
    Commented Sep 18, 2014 at 14:43
0
public class DataInsideArrays { 
    public static DataInputStream a = new DataInputStream(System.in);
   List<String> productname=new ArrayList<String>();

    public static void main(String args[]) throws Exception {
        // rest of your code...
        if(code == 1) { 
            System.out.print("") ; 
            System.out.print("Product number: ");
            System.out.print("Product name: "); 
            String prodname = a.readLine(); 
            System.out.print("Price: "); 
            int price = Integer.parseInt(a.readLine()); 
            System.out.println(""); 

  ////////////////////////to store data place  arraylist here/////////////////////////////
           productname.add(prod);

  /////////////////////  //same way use arr to store price and product no
        } else if(code == 2) {
            System.out.println("Display List of Products-Prices") ;
            System.out.print("Enter product number:") ; 
            int prodnum=Integer.parseInt(a.readLine()); 
            System.out.println("");
        }
        if(code == 3) { 
            System.out.println("Invalid");        
            System.out.println("Restart");
            System.out.println(""); 
        }
    }
}
7
  • It doesn't need to be on top of the rest of the codes?
    – Axiom_CC
    Commented Sep 18, 2014 at 14:10
  • on the top its only array declaration and if you will declare in inside if then it wont be accessible outside that if
    – kirti
    Commented Sep 18, 2014 at 14:15
  • arrprodname[i] = prodname; this won't work because you didn't initialize your array. Also, you can't do it because you don't know the size.
    – Narmer
    Commented Sep 18, 2014 at 14:16
  • @Kirti hm. I somehow getting your idea. I'll try this one. Thank you very much!
    – Axiom_CC
    Commented Sep 18, 2014 at 14:16
  • 1
    If you want to try this you should initialize the array using static String[] arrprodname = new String[100];. Using 100 ensures that, in worst case, you always have room for new products. But it's a waste of memory.
    – Narmer
    Commented Sep 18, 2014 at 14:19
0

Here's the correct codes for the output I want. Maybe is there any other way I can get the same output of this with different coding?

import java.io.*;
import java.util.ArrayList;
public class DataArrays 
{ 
    public static DataInputStream a = new DataInputStream(System.in);
    public static void main(String args[])throws Exception
    {
        ArrayList<Integer> prodNum = new ArrayList<Integer>(100);
        ArrayList<String> prodName = new ArrayList<String>(100);
        ArrayList<Integer> prodPrice = new ArrayList<Integer>(100);
        ArrayList<Integer> prodPay = new ArrayList<Integer>(100);

        for(int x=1;x<=100;x++)
        {      
            System.out.println("1 - Maintenance");
            System.out.println("2 - Transaction");
            System.out.println("");

            System.out.print("Enter code: ");
            int code = Integer.parseInt(a.readLine());
            System.out.println("");

            int y = 1;
            if(code==1) 
            {
                System.out.print("") ; 
                System.out.println("Product number: "+ x);
                prodNum.add(x);             //this brings 1st input to array element #0 which is not needed
                prodNum.add(x);
                System.out.print("Product name: "); 
                String prodname = a.readLine(); 
                prodName.add(prodname);     //this brings 1st input to array element #0 which is not needed
                prodName.add(prodname);
                System.out.print("Price: ");
                int prodprice = Integer.parseInt(a.readLine());
                prodPrice.add(prodprice);   //this brings 1st input to array element #0 which is not needed
                prodPrice.add(prodprice);   
                System.out.print("Payment: ");
                int prodpay = Integer.parseInt(a.readLine());
                prodPay.add(prodpay);       //this brings 1st input to array element #0 which is not needed
                prodPay.add(prodpay);
                System.out.println("");
                System.out.println("Start New Transaction:");
                System.out.println("");
            }
            else if(code==2) 
            {
                System.out.println("Display List of Products-Prices"); 
                System.out.print("Enter product number: "); 
                int i = Integer.parseInt(a.readLine());
                i = prodNum.get(i);         //this gets the data stored in the arraylist. Assuming it starts with 1 and above
                prodNum.set(1, i);
                System.out.println("");

                System.out.println("Product name: "+ prodName.get(i));
                System.out.println("Product price: "+ prodPrice.get(i));
                System.out.println("Product payment: "+ prodPay.get(i));
                System.out.println("");
                System.out.println("Start New Transaction:");
            } 
            else if(code>=3) 
            { 
                System.out.println("Invalid");        
                System.out.println("Restart");
                System.out.println("");
            }
            else if(code==0)
            {
                System.out.println("Program will end");
                break;
        }}}}

Thank for helping me guys. Really appreciated it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.