Java Forum / First Aid / March 2006
Filling an array with values from the user
IanH - 01 Mar 2006 14:23 GMT Hi, I am currently trying to fill an array with values received from user input. As i'm quite new to java I'm not sure how to go about it. Here is a snipet of what i have been working on.(I'm want to be able record customer details of a car park and be able return the fee due, I have a function set up to calculate the charges. I then want to print a list of all the customers who used the car park yesterday and the fee due. ) Any help would be appreciated. public class CarPark extends JApplet { public void init () { int array []; // declare reference to an array
array = new int[ 10 ]; // create array
double minimumfee = 2.0; double additionalfee = 0.5; double maximumfee = 10.0; double Fee = 0; String name; String address; String creditCardDetails; String numberOfHours; int NoOfHours = 0;
String output = "Number\tName\tAddress\tCreditCardNumber\tNoOfHours\tTotalCharge"; JTextArea outputArea;
for (int counter = 0; counter < array.length; counter++ )
name = JOptionPane.showInputDialog( "Enter your name "); address = JOptionPane.showInputDialog( "Enter your address "); creditCardDetails = JOptionPane.showInputDialog( "Enter your credit card details "); numberOfHours = JOptionPane.showInputDialog( "Enter the number of hours "); output += counter + "\t" + array[ counter ] + "\n";
//create JTextArea and attach to Applet outputArea = new JTextArea();
public void calculateCharges( int fee) {
// convert numberOfHours to NoOfHours NoOfHours = Integer.parseInt( numberOfHours );
if ( NoOfHours <= 3 ) Fee = 2.00; else if ( NoOfHours > 3) Fee = (NoOfHours - 3 ) * .5 + 2.00; else if ( NoOfHours >=24 ) Fee = 10.00; } // end calculateCharges
Rhino - 01 Mar 2006 14:35 GMT > Hi, > I am currently trying to fill an array with values received from user [quoted text clipped - 52 lines] > Fee = 10.00; > } // end calculateCharges Do you have a specific question? If not, you shouldn't expect too many replies to your post. You can't just post a fragment of what you have done and expect us to finish your homework for you.
Ask some specific questions like: - Why do I get a compile error (specify the error!) for this statement: XXXX? - Why does the calculated fee come out as 0 when the fee should be $5 for so many hours of parking? - Why do I get a NullPointerException on this line (specify the line)?
-- Rhino
IanH - 01 Mar 2006 14:58 GMT My question is: "How to ask users for input and store these values in an array
> > Hi, > > I am currently trying to fill an array with values received from user [quoted text clipped - 66 lines] > -- > Rhino Rhino - 01 Mar 2006 15:41 GMT > My question is: "How to ask users for input and store these values in > an array Do you know how to write a GUI in Java? If yes, you could display a form of some kind to the users with questions that have text fields beside them for them to enter the data. If you are writing an application or applet, you'd likely use Swing (or maybe AWT or SWT) to compose the GUI; if you are writing a servlet, you'd like use HTML to compose the form.
If you're not familiar with writing GUIs - and if you're not, you probably won't have the time to learn before your homework is due - you can display a question at the command prompt and wait for the user to reply, then store the reply in your program. Where you store it is up to you but an array is definitely one of the possibilities.
Which approach do you prefer? Depending on your answer, I may have some small examples I could post illustrating the techniques....
-- Rhino
>> > Hi, >> > I am currently trying to fill an array with values received from user [quoted text clipped - 68 lines] >> -- >> Rhino IanH - 01 Mar 2006 16:24 GMT I think i'll use the user prompt as i havn't much time and its the one i'm most familiar with. I seem to be having problems with passing the fee. I'm not sure what i'm doing wrong. There is what i have done so far.
import java.awt.Container; import javax.swing.*;
public class PassArray extends JApplet {
// initialize applet public void init() { JTextArea outputArea = new JTextArea(); Container container = getContentPane(); container.add( outputArea ); String name; String address; String creditCardNumber; String hours; int noOfHours;
String array[]; //declared array array = new String[ 1 ]; //create array
String output = "Customer Name\tAddress\tCreditCardNumber\tHours\tFee\n";
name = JOptionPane.showInputDialog("Enter your name"); address = JOptionPane.showInputDialog("Enter your address"); creditCardNumber = JOptionPane.showInputDialog("Enter your credit card number"); hours = JOptionPane.showInputDialog("Enter total hours");
// convert numberOfHours to NoOfHours noOfHours = Integer.parseInt( hours );
// append original array elements to String output for ( int counter = 0; counter < array.length; counter++ ) output += name + "\t" + "\t" + address + "\t" + creditCardNumber + "\t" + "\t" + hours + "\t" +noOfHours + "\n"; //output += " " + array[ counter ];
calculateCharges( noOfHours ); // array passed by reference
outputArea.setText( output );
} // end method init
// multiply each element of an array by 2 public void calculateCharges( int fee) { double Fee; int NoOfHours = 0;
if ( NoOfHours <= 3 ) Fee = 2.00; else if ( NoOfHours > 3) Fee = (NoOfHours - 3 ) * .5 + 2.00; else if ( NoOfHours >=24 ) Fee = 10.00; }
} // end class PassArray
Rhino - 01 Mar 2006 17:43 GMT >I think i'll use the user prompt as i havn't much time and its the one > i'm most familiar with. I seem to be having problems with passing the [quoted text clipped - 61 lines] > > } // end class PassArray The code you have to prompt for the information and display it works fine in my AppletViewer.
The problem with the fee happens is in the calculateCharges method: you define an input parameter named 'fee' (all lower case) that is an int, then you immediately create another variable named 'Fee' (capitalized) that is a double. You then calculate a value for 'Fee' but then never refer to it again; I would have expected you to at least try to display that value somewhere in your outputArea. To complicate matters further, the input parameter called 'fee' is called 'noOfHours' when you pass it to the calculateCharges method; that suggests further confusion on your part about exactly what you are trying to do.
I think you need to modify the definition of calculateCharges so that it receives 'numberOfHours' as an input and returns 'fee' as an output; then, in your init method, after you have calculated the fee, display it in the outputArea.
Something like this:
public double calculateCharges(int hoursParked) {
double fee = 0.00; //initialize the output of the method
/* Calculate fee. */ if (hoursParked <= 3) fee = 2.00; ...
return fee; }
The invocation of the calculateCharges method should be something like this:
double charges = calculateCharges(noOfHours);
Then, be sure to display the value of 'charges' in your outputArea, perhaps by including it in the 'output' variable you create in your for loop.
Please note that the revised calculateCharges method refers to 'noOfHours' as 'hoursParked' within the method signature and the return value named 'fee' within that method is called 'charge' in the init method; that was deliberate to show you that the names don't have to be the same as long as the datatypes match. However, you could use 'noOfHours' where I have 'hoursParked' and 'charge' where I have 'fee' and everything will still work.
The other main change I made was to make calculateCharges return the fee/charge as the output from the method. If you had to describe the purpose of calculateCharges, I think you would agree that it was supposed to calculate the parking fee given the number of hours that the customer had parked so it seemed logical to make the fee the value returned by the method and to make the hours parked the input.
Does this make sense to you?
Also, a few style things; your instructor may not care to much about style at this stage and the same might apply to you but I think it's a good idea to develop good habits early. Two things that will help you (and others) read and understand your code are: - use consistent indentation for your code. I know that newsreaders tend to mangle indentation so yours may already be perfect but it was definitely ragged in my newsreader. - a variable name shouldn't start with a capital letter (as in the case of 'Fee' and 'NoOfHours') with the exception of constants, which should be written entirely in capitals.
-- Rhino
IanH - 01 Mar 2006 19:04 GMT Thanks for your help. I now understand what i was doing wrong. Just one more question. At the moment i have the array set up to only hold 1 customers details, however, i would like to hold more. I changed array = new String[ 1 ]; //create array to array = new String[ 2 ]; //create array (changing 1 to 2) and the customer details were printed twice on the screen. Is there a way i can change this. I also tried a do while loop but that didn't work either.
//do { name = JOptionPane.showInputDialog("Enter your name"); address = JOptionPane.showInputDialog("Enter your address"); creditCardNumber = JOptionPane.showInputDialog("Enter your credit card number"); hours = JOptionPane.showInputDialog("Enter total hours");
//} while ( name != null );
Rhino - 01 Mar 2006 19:58 GMT > Thanks for your help. I now understand what i was doing wrong. Just > one more question. At the moment i have the array set up to only hold [quoted text clipped - 12 lines] > > //} while ( name != null ); Arrays have one ugly attribute that make them unattractive for the applet you are writing: once you've defined them to hold 'n' elements, that's it, you can't add any more. Therefore, if you think you're going to get a maximum of 10 elements in your array and then an 11th comes along, you find that the array is full and won't accomodate the 11th element. Now, if that happens, you can programmatically create a new bigger array, copy the elements from the old array over to the new, and so forth but in a case where I didn't know the maximum number of elements to expect, I'd prefer to use something that can be expanded to as many elements as I get.
The most obvious thing for a newbie to use would be a Vector; they've been around from the beginning of Java and are very good for this purpose. One of the Collections classes, like ArrayList, may be even better in some respects. Collections have been around for a few years but I don't know if they are typically taught in courses; they might be considered too advanced. Then again, you may get bonus points for using them; it really depends on your instructor.
Do you have any feeling for what your instructor would want? Do you have any preference for which of these solutions you'd prefer to use?
An array would still be a workable approach. I'd simply set the array capacity to something that I don't expect ever to exceed; so, if I was told 10 was the maximum, I'd err on the side of caution and make the size 20 or 100, just in case the initial expectation was overly low.
Also, one observation on the design aspects of this: using arrays (or Vectors or Collections) for this program seems somewhat unrealistic to me since it doesn't mirror real life. I'm picturing the guy in the kiosk/booth who is collecting the fee from the people leaving the parking area. Do you think he is really going to obtain the names, addresses, and hours parked for several people, then fire up a program to compute the fees for all of these people? Or is he more likely to collect the information for one customer, calculate the fee, and collect the fee from that customer, then start all over for the next customer? Unless parking works a lot differently in the UK than it does here in Canada, I think you'd only handle one customer at a time, which makes the array/Vector/Collection unnecessary. School assignments aren't that terribly realistic sometimes so it's fine to pretend that you would actually process customers the way your assignment requires. However, I would always have real life in mind when trying to analyze problems and design solutions. By the same token, I've never been asked for my name and address when paying for parking.
In any case, if you tell me which approach you'd like to take, I can try to give you a few lines of code and an explanation, along with some links where you can learn more.
-- Rhino
IanH - 02 Mar 2006 14:26 GMT I think maybe setting the capacity higher than it would ever exceed would be the best approach for me.
Rhino - 02 Mar 2006 19:01 GMT >I think maybe setting the capacity higher than it would ever exceed > would be the best approach for me. Okay, then we'll stick with a String array.
You already know how to create the array and set its size; choose a size that is big enough to contain all the parking customers you ever expect to see on the busiest day.
I think you need two loops: 1. A loop that has the job of asking for all the information for each parking customer who wants to pay for their parking. Each iteration of the loop needs to store the information in the array; each customer should be one element of the array and that element should probably be the print line that contains the customer information and the fee. 2. A loop to display the customer information and fee for each customer who is in the array.
You need to execute the first loop until all the necessary customer information has been accumulated.
The fee for each customer could be calculated as the customer information is accumulated or it could be calculated as you display the contents of the array; I would probably do it in the first loop, not the second, so I'm going to assume that you will do it that way too.
You will need to have some way of ending the first loop when you have information for all of the customers. There are many ways to do this but I'd suggest that the simplest is the traditional approach: look at the value that you get for the customer name. If it is not blank, proceed to get the rest of the customer's information and store it in the array. If it is blank, assume that there are no more customers and get out of the loop.
The second loop is much easier; just display each line of the array and stop when you have displayed the last customer. You can get the size of the array with this expression: array.length. Use that expression to control the second loop. If you are using Java 1.5.0, there is an even easier way to do it: use the new form of the 'for' loop.
For example:
for (String oneCustomer : array) { //display one line of the array }
I have deliberately not written much code and described things in words instead. You will learn more if you try to think of things the way I have described and then write your own code than if I simply write all the code for you. The statements you need are not very hard and you seem to know all or most of them already; what you need to learn is how to design the program logically so that it does what you want.
Try doing what I've suggested and post back if you don't understand with specific questions. I will try to give you hints to point you in the right direction but I will try to avoid writing the entire solution.
-- Rhino
IanH - 02 Mar 2006 20:13 GMT Just one quick question before i start, can i still call the funtion calculateCharges in the first loop?
Rhino - 02 Mar 2006 20:47 GMT > Just one quick question before i start, can i still call the funtion > calculateCharges in the first loop? Yes, absolutely! But the Java term is "method", not "function" :-)
-- Rhino
IanH - 02 Mar 2006 21:51 GMT Hi, have been working on the first loop. I understand that there is a problem with output = array[num]; but not sure how i should change it. Also I have been rearranging code and and compiler does not recognise the variable name at the end of the do loop.
import java.awt.Container; import javax.swing.*;
public class PassArray extends JApplet {
// initialize applet public void init() { JTextArea outputArea = new JTextArea(); Container container = getContentPane(); container.add( outputArea ); String name; String address; String creditCardNumber; String hours; int noOfHours;
String array[]; //declared array array = new String[ 5 ]; //create array
String output = "Customer Name\tAddress\tCreditCardNumber\tHours\tFee\n"; do { for (int num = 0; num <= array.length; num++)
name = JOptionPane.showInputDialog("Enter your name"); address = JOptionPane.showInputDialog("Enter your address"); creditCardNumber = JOptionPane.showInputDialog("Enter your credit card number"); hours = JOptionPane.showInputDialog("Enter total hours"); output = array[num];
} while ( name != null );
// convert numberOfHours to NoOfHours noOfHours = Integer.parseInt( hours ); double charges = calculateCharges(noOfHours);
// append original array elements to String output for ( int counter = 0; counter < array.length; counter++ ) output += name + "\t" + "\t" + address + "\t" + creditCardNumber + "\t" + "\t" + hours + "\t" + charges + "\n";
outputArea.setText( output );
} // end method init
// multiply each element of an array by 2 public double calculateCharges(int hoursParked) { // public void calculateCharges( int fee){ double fee = 0.00; //initialize the output of the method int NoOfHours = 0;
if ( hoursParked <= 3 ) fee = 2.00; else if ( hoursParked > 3) fee = (hoursParked - 3 ) * .5 + 2.00; else if ( hoursParked >=24 ) fee = 10.00; return fee; }
} // end class PassArray
Rhino - 02 Mar 2006 22:21 GMT > Hi, > have been working on the first loop. I understand that there is a > problem with output = array[num]; but not sure how i should change it. You need to reverse the assignment statement; you are assigning 'output' to the array position, not vice versa.
> Also I have been rearranging code and and compiler does not recognise > the variable name at the end of the do loop. I just did a quick check and verified my suspicion: the variable that is the loop controller must be defined outside of the loop for it to be recognized in the while expression. For example, given:
============================= int num = 1;
do {
System.out.println("num = " + num);
num++;
} while (num < 10);
============================= the loop will work fine.
But given this:
============================= do {
int num = 1;
System.out.println("num = " + num);
num++;
} while (num < 10);
=============================
you will find that the loop never executes because 'num' is not defined. (Actually, it _is_ defined but it's not defined where Java can see it in time.) So, move the definition of your loop controller variable outside of the loop.
Also, I think you want to change the test in your while statement; if no name value is provided in the loop, I think you'll find that the name variable contains "", not null. (Try it for yourself to be sure.)
> import java.awt.Container; > import javax.swing.*; [quoted text clipped - 60 lines] > > } // end class PassArray IanH - 05 Mar 2006 13:38 GMT Hi I'm still having problems with the following Its output = num[array]; that is giving me trouble. Its saying that it cannot find the symbol num. I can't see a way to fix it.
do { for (int num = 0; num <= array.length; num++)
JOptionPane.showInputDialog("Enter your name"); address = JOptionPane.showInputDialog("Enter your address"); creditCardNumber = JOptionPane.showInputDialog("Enter your credit card number"); hours = JOptionPane.showInputDialog("Enter total hours");
output = num[array]; } while ( name != "" );
Yereax Johnsen - 05 Mar 2006 16:36 GMT I am not an expert, but I am wondering about:
> do { > for (int num = 0; num <= array.length; num++) int num is an integer and
> output = num[array]; num is an array? is this possible in Java? cYa Yere
Free MagazinesGet these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...
|
|
|