14 Replies - 668 Views - Last Post: 17 November 2011 - 06:02 PM Rate Topic: -----

#1 shannon_p  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 31
  • Joined: 10-November 11

Run Error?

Posted 16 November 2011 - 10:36 AM

I am writing a java program that shops. When I run the program it stops and I don't know why because I have no errors in my code. Someone please help.
 public static void main(String[] args) {
        shopping [] shop = new shopping[100];
        PrintWriter ofile = null;
        String pname = null;
        double pprice = 0, total = 0;
        String pbarcode = null;
        int ibarcode = 0;
        int pquantity = 0;
        int cmd, size = 0;
        int num;
        boolean done;
        shopping p = new shopping();    
        String resp = JOptionPane.showInputDialog("Choose from:" +
                "\n1: Add new products\n2: Manage existing file\n3: Shop ");
        cmd = Integer.parseInt(resp);
        String sinput = null;
        switch(cmd){
        case 1: done = false;
              int i = 0;
               while(!done){                  
                sinput = JOptionPane.showInputDialog("Enter the product name");                          
                    p.setname(sinput);
                sinput = JOptionPane.showInputDialog("Enter the quantity of that product");
                    pquantity = Integer.parseInt(sinput);
                    p.add(pquantity);
                sinput = JOptionPane.showInputDialog("Enter the barcode");
                    ibarcode = Integer.parseInt(sinput);
                    p.setbar(pbarcode);
                sinput = JOptionPane.showInputDialog("Enter the price of that item");
                    pprice = Double.parseDouble(sinput);
                    p.setprice(pprice);
                    i++;
                    resp = JOptionPane.showInputDialog("Enter another item? 1: yes 0: no");
                    cmd = Integer.parseInt(resp);
                    if(cmd == 0)
                        done = true;
                    size = i;
                    
                      }
                    resp = JOptionPane.showInputDialog("Enter name of file for this store");

                    try {
                        ofile = new PrintWriter(new File(resp));
                    }
                    catch(FileNotFoundException e){
                        System.out.println("Could not open file");
                    }
                    for(i = 0; i < size; i++){
                        ofile.println(shop[i].getname());
                        ofile.println(shop[i].getprice());
                        ofile.println(shop[i].getbar(resp));
                    }
                    ofile.close();
                break;



Is This A Good Question/Topic? 0
  • +

Replies To: Run Error?

#2 Fuzzyness  Icon User is offline

  • Comp Sci Student
  • member icon

Reputation: 669
  • View blog
  • Posts: 2,438
  • Joined: 06-March 09

Re: Run Error?

Posted 16 November 2011 - 10:44 AM

witch(cmd){

If cmd isn't 1, then nothing will happen with your code. You only have the switch statement set up for case 1. I am not sure if that is all of your code seeing as how just cuts off after the first case. So if there is more please post it all.
Was This Post Helpful? 0
  • +
  • -

#3 shannon_p  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 31
  • Joined: 10-November 11

Re: Run Error?

Posted 16 November 2011 - 11:05 AM

I have a few errors in my other cases but im concerned about case 1. it was fine until i added the price feature and now it stops after barcode.

 public static void main(String[] args) {
        shopping [] shop = new shopping[100];
        PrintWriter ofile = null;
        String pname = null;
        double pprice = 0, total = 0;
        String pbarcode = null;
        int ibarcode = 0;
        int pquantity = 0;
        int cmd, size = 0;
        int amt;
        boolean done;    
        String resp = JOptionPane.showInputDialog("Choose from:" +
                "\n1: Add new products\n2: Manage existing file\n3: Shop ");
        cmd = Integer.parseInt(resp);
        String sinput = null;
        switch(cmd){
        case 1: done = false;
              int i = 0;
               while(!done){    
                   shopping p = new shopping();
                sinput = JOptionPane.showInputDialog("Enter the product name");                          
                    p.setname(sinput);
                sinput = JOptionPane.showInputDialog("Enter the quantity of that product");
                    pquantity = Integer.parseInt(sinput);
                    p.add(pquantity);
                sinput = JOptionPane.showInputDialog("Enter the barcode");
                    ibarcode = Integer.parseInt(sinput);
                    p.setbar(pbarcode);
                sinput = JOptionPane.showInputDialog("Enter the price of that item");
                    pprice = Double.parseDouble(sinput);
                    p.setprice(pprice);
                    i++;
                    resp = JOptionPane.showInputDialog("Enter another item? 1: yes 0: no");
                    cmd = Integer.parseInt(resp);
                    if(cmd == 0)
                        done = true;
                    size = i;
                    
                      }
                    resp = JOptionPane.showInputDialog("Enter name of file for this store");

                    try {
                        ofile = new PrintWriter(new File(resp));
                    }
                    catch(FileNotFoundException e){
                        System.out.println("Could not open file");
                    }
                    for(i = 0; i < size; i++){
                        ofile.println(shop[i].getname());
                        ofile.println(shop[i].getprice());
                        ofile.println(shop[i].getbar(resp));
                        ofile.println(shop[i].getquantity());
                    }
                    ofile.close();
                break;
        case 2: resp = JOptionPane.showInputDialog("Enter the name of the file");
                    Scanner infile = null;
                    try {
                        infile = new Scanner(new File(resp));
                    }
                    catch(FileNotFoundException e){
                        System.out.println("File Not Found");
                        System.exit(0);
                    }
             i = 0;
                    while(infile.hasNext()){
                        pname = infile.nextLine();
                        pprice = infile.nextLine();
                        ibarcode = infile.nextInt();
                        pquantity = infile.nextInt();
                        resp = infile.nextLine();
                        shopping p = new shop(pname, pprice, pquantity, pbarcode);
                        shop[i] = p;
                        i++;
                    }
        case 3: JOptionPane.showInputDialog("Enter the barcode of the item you would like to buy");
            
            JOptionPane.showInputDialog("Enter how many you would like to buy");
             amt = Integer.parseInt(sinput);
            if(amt <= pquantity){
                JOptionPane.showInputDialog("You bought " + amt);
                amt = shop[i].buy(amt);
                total = total + pprice;
            }
            else
                JOptionPane.showInputDialog("There are not that many to buy");
             
             resp = JOptionPane.showInputDialog("Buy another item? 1: yes 0: no");
                    cmd = Integer.parseInt(resp);
                    if(cmd == 0)
                        done = true;
            break;

               
                    
        }
    }
}


Was This Post Helpful? 0
  • +
  • -

#4 shannon_p  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 31
  • Joined: 10-November 11

Re: Run Error?

Posted 16 November 2011 - 11:19 AM

opps I forgot my class
class shopping {
    private String name;
    private double price;
    private String barcode;
    private int quantity;
    public shopping(){
        name = "unknown";
        price = 0;
        barcode = "unknown";
        quantity =0;
    }

    shopping(String pname, String pbarcode, double pprice, int pquantity) {
        name = pname;
        barcode = pbarcode;
        price = pprice;
        quantity = pquantity;
        this.add(quantity);
        this.buy(quantity);       
    }
  
    public void setname(String item){
        name = item;
    }
    public String getname(){
        return name;
    }
    public void setprice(double cost){
        price = cost;
    }
    public double getprice(){
        return price;
    }
    public void setbar(String bar){
        barcode = bar;
    }
    public String getbar(String bar){
        return barcode;
    }
    public void setquantity(int num){
        quantity = num;
    }
    public double getquantity(){
        return quantity;
    }
    public void add(int amt){
        quantity = quantity + amt;
    }
    public double add(){
        return quantity;
    }
    public void buy(int amt){
        quantity = quantity - amt;
    }
    public double buy(){
        return quantity;
    }


    }


Was This Post Helpful? 0
  • +
  • -

#5 smohd  Icon User is offline

  • Critical Section
  • member icon


Reputation: 1820
  • View blog
  • Posts: 4,627
  • Joined: 14-March 10

Re: Run Error?

Posted 16 November 2011 - 11:46 AM

Can we see the setbar() method please? because if it stops after asking the bar code, then the problem will probably be in that method forget about that ;)

The problem is with your setbar() method, it is required to pass String according to your definition:
 public void setbar(String bar){
but you pass an integer there:
ibarcode = Integer.parseInt(sinput);
p.setbar(pbarcode);

So it is giving error that is why it stops, it cant find the method which passes integer.

This post has been edited by smohd: 16 November 2011 - 11:51 AM

Was This Post Helpful? 0
  • +
  • -

#6 Fuzzyness  Icon User is offline

  • Comp Sci Student
  • member icon

Reputation: 669
  • View blog
  • Posts: 2,438
  • Joined: 06-March 09

Re: Run Error?

Posted 16 November 2011 - 11:49 AM

public void setbar(String bar){
        barcode = bar;
    }

He posted it in his other class, it is pretty simple nothing changes too much and no room for errors.

What all did you change when you added the price feature?
Was This Post Helpful? 0
  • +
  • -

#7 smohd  Icon User is offline

  • Critical Section
  • member icon


Reputation: 1820
  • View blog
  • Posts: 4,627
  • Joined: 14-March 10

Re: Run Error?

Posted 16 November 2011 - 11:59 AM

No mistake again, I misread it, you are passing pbarcode which is null, I thought you passes the one which you parsed to integer but you passes pbarcode which was initialized to null and never give any value after that: String pbarcode = null;
Was This Post Helpful? 0
  • +
  • -

#8 Fuzzyness  Icon User is offline

  • Comp Sci Student
  • member icon

Reputation: 669
  • View blog
  • Posts: 2,438
  • Joined: 06-March 09

Re: Run Error?

Posted 16 November 2011 - 12:11 PM

smohd is right. Your problem lies with this section actually just not the fact it is null, doesn't matter it would just set the value to null and life went on.

Look at this:
sinput = JOptionPane.showInputDialog("Enter the barcode");
ibarcode = Integer.parseInt(sinput);
 p.setbar(pbarcode);


You get the int version of the barcode by giving it to ibarcode, however you never assign pbarcode to anything. So what you need to do is send it the String version of the barcode, which you have stored in sinput still. So if you change out pbarcode with sinput it should work better.

p.setbar(sinput);

I am not sure what you expect assigning ibarcode to do, if there is more than 1 entry it will get written over and doesn't do anything after that. Also you I think you are going about creating these objects wrong. Instead of using the set method separately why not just create the object then set whatever is left over. Here is what I mean:
shopping(String pname, String pbarcode, double pprice, int pquantity)
pname = JOptionPane.showInputDialog("Enter the product name");
pbarcode = // prompt JOptionpane for it
pprice = Double.parseDouble(/* Joptionpane for the string version of it*/)
pquantity = Integer.parseInt(/* JOptionpane for the string version of it*/)
Shopping p = new Shopping(pname, pbarcode, pprice, pquantity);
// here is where you use any setter methods for the other values not in constructor
/* This is where you need to Add it to an array see below comments */


Alright, now you create the while loop, create the object in the loop and get all the values and set them etc. You never add it to the array before the while loop ends, so the object gets discarded, and if the loop cycles through again it just creates another object, and at the end of that iteration, will discard the object and you will have accomplished nothing.

See what I am saying?

This post has been edited by Fuzzyness: 16 November 2011 - 12:12 PM

Was This Post Helpful? 1
  • +
  • -

#9 shannon_p  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 31
  • Joined: 10-November 11

Re: Run Error?

Posted 16 November 2011 - 12:43 PM

so your saying do all my sets outside of the while loop?
Was This Post Helpful? 0
  • +
  • -

#10 shannon_p  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 31
  • Joined: 10-November 11

Re: Run Error?

Posted 16 November 2011 - 12:59 PM

:) Okay I did what you said and it goes through all my features now :)
Im lost on what you mean by the while loop. Honestly, loops confuse me. :(
Was This Post Helpful? 0
  • +
  • -

#11 Fuzzyness  Icon User is offline

  • Comp Sci Student
  • member icon

Reputation: 669
  • View blog
  • Posts: 2,438
  • Joined: 06-March 09

Re: Run Error?

Posted 16 November 2011 - 01:02 PM

Ok well I am at work right now and can't explain it but later tonight (like later in 5 hours or so) I will post a long elaborate explanation of what i am talking about and what you can do, just don't have time right now though. y apologies!
Was This Post Helpful? 0
  • +
  • -

#12 shannon_p  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 31
  • Joined: 10-November 11

Re: Run Error?

Posted 16 November 2011 - 01:11 PM

well that would be great!!! Thank you so much for your help. I am really struggling with this program and it's making me really, really upset. I wanna give up :(
Was This Post Helpful? 0
  • +
  • -

#13 Fuzzyness  Icon User is offline

  • Comp Sci Student
  • member icon

Reputation: 669
  • View blog
  • Posts: 2,438
  • Joined: 06-March 09

Re: Run Error?

Posted 17 November 2011 - 11:17 AM

Alright, sorry that I lied, got caught up doing other things last night. So, loops, here we go!

The basis to every loop whether, it be a for loop, while loop, or a do while loop, is that they are conditions. A loop will only iterate, meaning perform the code inside of it, if the condition is met. How do you tell if a condition is met? Well it is either Yes, condition met, or No, condition not met. In java, Yes and No mean True and False. Three out of the four types of loops use conditionals.

Types:
For loop
While Loop
Do While Loop
For Each Loop

We will take a look at the first three for now, I will address the For Each Loop at the end for it acts a little bit differently from the other three.

For Loop:
There are 4 parts to the set up for the For loop when creating one. First you need the keyword to tell jdk what it is, second you need a control variable, then you need a condition, and then you need increment. Lets take a look at the set up for the for loop below:

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

for - This is the first part, the keyword. This tells the jdk that you are starting a loop, without this, well it wouldn't be a for loop!

int i = 0; - This is the second part, the control variable. This will be the start for the condition. One of the most common uses for the for loop is to cycle through an array of some sort, usually this control variable would be the index you want to start at. The control variable could be anything you set it to usually.

i < array.length; - This is the third part, the conditional. This is where the True False portion of the for loop comes in. Using the example of an array, lets say the array.length is hold the value of 4. Since we set i to 0. We know the condition is a true false situation so here is what you can get from that...
Is 0 < 4 ? Yes - True. Will execute code in the loops brackets
Is 1 <4 ? Yes - True. Execute Code.
Is 2 <4 ? Yes - True. Executes code.
Is 3 <4 ? Yes - True. Executes Code.
Is 4 <4 ? No. False. It will not perform the code in the for loop and it will move onto the next line of code in the program since the condition is no longer met.
The conditional is usually the main problem of for loops, mainly because it is the main cause for ArrayOutOfBoundsException errors. Between the control variable and the Conditional, they have to work properly. The method array.length has the value of 4, since the size of the array is 4. So, you have to know about the class you are using with the loop in order to make the conditional work way you want it to. Why did we put the conditional to stop at less than 4? I mean the size is 4 so don't we want it to include 4? If you were to make the conditional i <= 4 so that it includes 4, what do you think would happen?
Result: ArrayIndexOutOfBoundsException : 4
This is what I meant about know about the class, in an Array and ArrayList and any set, the index starts at 0. So if you were to do 0-4, 4 being inclusive, it executes 5 times; however your array size is only 4!
This is why the conditional is so important, it is the one thing that keeps the for loop going or stopping. If this is incorrect than you will not have the expected output you want or you may even get a runtime error! In order to know your conditional is correct you need to know 3 things:
1. What you want to do with the for loop
2. The Class that you are using with the for loop
3. Booleans

i++ - The last part of the for loop, the increment. Now after I made that huge section with the conditional how could this part be even remotely important?! Well, it is just as important as the Conditional. The increment determines if the conditional is ever met! Say you have the i<array.length, that being 4. If you have the increment to i++; which is equivalent to i= i+1; it will increase the index by 1 each time. If you had it to i+=2, equivalent to i = i+2; you will only get every other index in the array. You could also mess up writing i = i+1 and only put i = i; this will create a infinite loop and crash your program. So you see how increment can be important? It is the 2nd control to your for loop, the first being the conditional. Generally however, in the example with the array, you will almost always see i++, unless you are trying to get every other index which would make it i+=2.

While Loop:
The while loop is a little bit different, basically it acts unlike a for loop where it executes a certain amount of times and be done. A while loop you have to have your own control for it, you usually use a while loop purely as a boolean, because ultimately that is what controls loops remember?

I like to think of the while loop as an if statement and a for loop put together. A while loop is like a custom for loop, it allows you to perform different operations a little bit differently. So here we go, lets analyze this code:

int i = 0;
boolean done = false;
while(!done && i < array.length)
{
	System.out.println(array[i]);
	if(array[i] > 100)
		done = true;
	i++;
}


Alright, lets take a look here, depending what you need, you usually have some sort of counter and or a boolean that will control the condtional of the loop. In case you haven't already caught on, here is a break down:
These are your outer variables:
int i = 0;
boolean done = false;

The are outside of the loop so then once the loop is over you can still access them, also if you were to create them inside of the while loop it would recreate the variable after every iteration and create an infinite loop.

This is your conditional:

while(!done && i < array.length)
while is the Keyword to let the jdk know you are starting a while loop. Inside of the ( ) you have the condition. This is the "if statement" portion of it. The while loops code will only execute if the condition is true, so if you need to break it down just think, if condition is true, will execute. If(!done) execute. The && portion of it means that both statement have to be true. Has to be !done (! is an boolean operator meaning opposite) AND i HAS to be less than array.length. Both need to be true to execute.

Now, unlike a for loop, a while loop does not have an increment added into it. This is why in the code inside of the brackets, you have to have statements to change the variables yourself. So in this case we have 2 statements, one is incrementing the variable i. The other statement is checking for a number larger than 100 and it will set the boolean to true.
i++;
f(array[i] > 100)
		done = true;


These are the 2 statements that will act as the increment. They will control the condition. You will always increment i, and boolean could change depending on the statement. If the boolean does change before 1 is 4 or higher, what will happen?
The loop will end, the condition of (!done && i<array.length) will not be met anymore. !done, what is that? means !false, which opposite of false is true. Which is why it executed before. However, what if done = true? !true means false. Since the while loop conditional is like an if statement, if false && true = false. That is boolean operation. Both would have to be true in order to execute the code. Be careful with the controlling of how you exit the code, you do not want to end up in a infinite loop because you forgot to increment or change the control variables. (in this case the control variables were boolean done and int i)

Do While Loop:
Well, this will be the shortest section, take everything that you just learned from the while loop section, and apply it here. The only difference between this loop and the other 2.. It does not need a condition to begin, only to continue. So make sure that you will not have errors when it first executes, or plan accordingly. I will commonly see a try catch statement inside of a do while loop.

int i = 0;
boolean done = false;
do{
	System.out.println(array[i]);
	if(array[i] > 100)
		done = true;
	i++;
}while(!done && i < array.length);


This is the exact same code from the while loop section, just switched around. Pretty self explanatory.

For Each Loop:
The first thing that you need to know about the For each Loop... YOU HAVE TO HAVE JDK 5 OR HIGHER. I know that you are not hard at reading, the capitals are stressing the importance ;)
So, what is the for each loop? Why do we need that over the for loop? The difference between the loops is this, a for each loop is usually used with ArrayList and other Collections or data structures. You use a for each loop because it gives you direct access to the object. The way that you set up a for each loop is like this:

for(int i : array){/*code*/}

As you can see it uses the same keyword as the regular for loop, however the JDK will know the difference so don't fret over that.

int - This is the type of the objects in the collection.
i - this is just a variable name that you will use. This variable hold the object.
array - this is the collection, or the variable name of the collection

As you can see there is no conditional, there is no index, and there is no increment. The For each loop takes care of all of that stuff for you! You would normally only use this type of loop for things like Objects of a Custom class. Anything else you can usually use a regular for loop. An example of a for each loop would be like this:

for(int i : array)
{
    System.out.println(i);
}


Really easy way of printing out the elements in the array. Like I said though, you will usually just use a regular for loop for that. A real use for the for each loop would be something like this in a custom class:

int prices = Cart.get(0).getPrice(); // give a basic value to compare with
String name = Cart.get(0).getName();
for(Item item : Cart)
{
    if(item.getPrice() > prices)
          System.out.println(item.getName() + "Is more expensive than" + name);
    else System.out.println(item.getName() + " Is less expensive than" + name);
    prices = item.getPrice();
    name = item.getName();
}
System.out.println("Please list the items in cheapest to most expensive based on the information that was just given to you");



Small code to set up a problem for someone to solve. See how in the beginning I had to use the Arraylist name, the get method to get the object, then the method to get the price for default comparison? That is what you would have to do in a regular for loop, see how in the for each loop I had direct access to the object so all I had to do was call the getprice() method? That is the blessing of the for each loop.

Now, I do not know about performances which one is better, that would be a issue addressed by my favorite performance analyzer pbl!


The one thing that I cannot tell you about loops, are which one to use. You just need to assess the situation that you are in and decide which has the more benefits of using it.

Man.. I need to submit this as a tutorial.. would suck to have to rewrite all of this haha! If you need a tutorial on Boolean Operators you can check out this tutorial by a DIC member.
NeoTifa has a GREAT tutorial on those among other things in it, check out part 5.

Hope this helps clarify things with loops! :^:
Was This Post Helpful? 2
  • +
  • -

#14 Fuzzyness  Icon User is offline

  • Comp Sci Student
  • member icon

Reputation: 669
  • View blog
  • Posts: 2,438
  • Joined: 06-March 09

Re: Run Error?

Posted 17 November 2011 - 12:23 PM

As for any problems or errors with the code just simply ask and we can answer those. But what I mentioned before is that you do not want to create a blank Shopping object and call all of the setter methods, when you can just get 4 variables and put them in the params for the constructor like I did in my example above in post #8.
Was This Post Helpful? 0
  • +
  • -

#15 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8343
  • View blog
  • Posts: 31,890
  • Joined: 06-March 08

Re: Run Error?

Posted 17 November 2011 - 06:02 PM

Any for() loop can be written as a while() loop and vice-versa

for() loop are just a shortcut to write, in a more concise way, what can be achieve with more statements in a while() loop.

If you look at the code generated, it is the same, there is no for or while statement in bytecode so it is always

init index
loop_label:
test condition if false goto loop_done:
perform loop body
update index
goto loop_label
loop_done:

so performance wise, they are the same
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1