Assigning User input to an array

I

IanH

Hi
I want to store values received from the user in array and then to
output the values on the screen. I'm new to java and am having
problems setting up the array and assigning the values to the array.
Here is my code so far not sure where to go with it. My code is working
at the moment but the values i type into the input boxes don't appear
on the screen.

Also, i have a method that calculates the daily parking fee - this
works fine.

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";

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");

do {

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

output += " " + array[num] + name + address + creditCardNumber +
hours;
//array[num] = name + address + creditCardNumber + hours;

} while ( name != "" );


// 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
 
S

steve_marjoribanks

I could well be wrong (!) but I think you just need to re-paint the
applet once you have set the text of the outputArea?

Steve
 
R

Rhino

IanH said:
Hi
I want to store values received from the user in array and then to
output the values on the screen. I'm new to java and am having
problems setting up the array and assigning the values to the array.
Here is my code so far not sure where to go with it. My code is working
at the moment but the values i type into the input boxes don't appear
on the screen.

Also, i have a method that calculates the daily parking fee - this
works fine.

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";

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");

do {

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

output += " " + array[num] + name + address + creditCardNumber +
hours;
//array[num] = name + address + creditCardNumber + hours;

} while ( name != "" );


// 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

You're back ;-) I was watching for your return on the comp.lang.java.help
newsgroup but the thread looked like it had gone dead so I assumed you'd
finished your program on your own. I hope you don't mind me jumping in
again.

I'm not surprised your program isn't displaying anything yet; you never
actually assign anything to the array and it is the array you are displaying
in the outputArea. The line you commented out -

//array[num] = name + address + creditCardNumber + hours;

is very close to what you want, except that you probably want the calculated
fee on that line (as well as the spacing tabs between the different values).

But that's just your immediate problem; you'll bump into more as soon as you
try running this program. I think the input statements ought to be within
the loop, not before the loop. Also, you don't need the for loop within the
do loop; there are easier ways to keep your position with the array.

There are many subtly different ways to write this little program and I
don't want to hold any one of the many variants out as being unquestionably
superior. However, when I solved the problem, I felt that there was enough
code being executing within the input loop that it justified getting its own
method. I created a getCustomerInfo() method and invoked it from init(). I
passed the array to the getCustomerInfo() method as an input parameter and
specified boolean as the return value.

Then, within the getCustomerInfo() method, I prompted for the customer name;
if the name was blank, I exited the method with 'return false'. Otherwise,
if the name was not blank, I asked for the address, creditCardNumber, and
hours, converted the String version of the hours to an int, calculated the
parking fee, and created a line of information to the array that was
effectively just a long String. The String got assigned to the next
available entry of the array, the array index was incremented, and the
method returned true.

The getCustomerInfo() method was invoked in a simple do loop within the
init() method:

boolean customerAdded = false;
do {
customerAdded = getCustomerInfo(array);
} while (customerAddred == true);

The loop always executes at least once. The loop will keep executing until
you supply a blank customer name, i.e. press OK without typing a name when
you see the prompt for the customer name. As soon as you supply a blank
name, the getCustomerInfo() method will end and the loop itself will end.

Then the array gets copied into the outputArea. I use a very small loop to
append each String from the array into the outputArea. Remember, you can't
pass outputArea.setText() a String array as a parameter and have it work
correctly. However, you can write a simple for loop that appends each String
in the array to the outputArea (via its append() method).

With this design, you don't need to repaint() anything and the different
parts of the program are reasonably well compartmentalized.

This explanation leaves out a couple of details, like how the header is
handled and how to remember your position in the array but I'll let you ask
about this in a followup question if you decide to try the approach I'm
suggesting.

Like I said, there are dozens of ways to write this small program and the
way that you are going can certainly be made to work without doing it quite
the way I'm suggesting. You may prefer to keep going the way you are now.
 
R

Roedy Green

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");

You can't very well start asking questions before you even have a
screen up there. I would either:

1. run this as an application rather than an Applet.

2. use a button in the Applet to trigger the question dialogs.
 
I

IanH

Hi,
I'm still trying to figure out my problem. I think I'll stick with the
way i'm writing the program at the moment. I have a couple of
questions though.
1. I now have my input statements within the loop but i have an error
message saying it cannot find the variable num
array[num] = name + address + creditCardNumber + hours ;
2. If I leave out the for loop within the do loop, I'm not sure how
else to keep my position within the array.
3. If i include the calculated fee on this line (//array[num] = name
+ address + creditCardNumber + hours; )
will i have to declare it before this as in include it within the do
loop

// convert numberOfHours to NoOfHours
noOfHours = Integer.parseInt( hours );
double charges = calculateCharges(noOfHours);

Any help would be very much appreciated.
 
R

Rhino

IanH said:
Hi,
I'm still trying to figure out my problem. I think I'll stick with the
way i'm writing the program at the moment. I have a couple of
questions though.
1. I now have my input statements within the loop but i have an error
message saying it cannot find the variable num
array[num] = name + address + creditCardNumber + hours ;
2. If I leave out the for loop within the do loop, I'm not sure how
else to keep my position within the array.

Your first two questions are aspects of the same problem. You need an int
variable that contains the value of the current position within the array.

As you probably know, arrays in Java are 0-based, i.e. given an array
defined as:

String[] myArray = new String[5];

the different 'slots' (or 'positions') within the array are identified as:
- myArray[0]
- myArray[1]
- myArray[2]
- myArray[3]
- myArray[4]

-NOT-

- myArray[1]
- myArray[2]
- myArray[3]
- myArray[4]
- myArray[5]

The thing in the square brackets goes by many different names, but is
essentially an index to the array: in the expression myArray[0], '0' is an
index that identifies the first 'entry', 'slot', 'position', 'bucket', etc.
within the array.

When you fill your array, you are going to want to fill the 'slots' in
order, starting at 0 and incrementing the index by 1 each time until you
have captured all of the data. Since you are displaying a report, you are
going to probably put the header in slot 0, then put up to 4 Strings in the
remaining slots. Each of those Strings are going to be a single line of
information about a single customer; that String will be a concatenation of
the customer name, address, credit card number and the fee that you
calculate for his/her parking.

All you really need to do to solve your first two questions is to create the
int variable that will point to the next available slot within the array.
Call it whatever you like but 'index' or 'num' wouldn't be too bad. Now, you
will need to be careful about a couple of things:
- where this variable is declared; it should be declared BEFORE you get into
the input loop
- the value to which the variable is initialized; remember, you want it to
indentify the next available slot in the array so what value will you want
to initialize it to?

Also, you will need to be sure that you increment this variable after
writing to it; if you don't do that, each line will be written to the same
slot, clobbering the previous value. The classic way to increment an int is:

index = index + 1;

but Java offers you a short form:

index++;

Why don't you try to add this code to the program and see what happens when
you run it?
3. If i include the calculated fee on this line (//array[num] = name
+ address + creditCardNumber + hours; )
will i have to declare it before this as in include it within the do
loop

// convert numberOfHours to NoOfHours
noOfHours = Integer.parseInt( hours );
double charges = calculateCharges(noOfHours);
I'm not sure what you mean by "declaring it with an include"? The 'include'
keyword is used to specify external _classes_ that need to be accessed by
your program; the 'array[nu] = ....' line is not a class so you won't need
an 'include' statement to make it work.

I think the problem that prevented that line from compiling earlier was that
num was not defined or was not defined correctly. 'num' is the int variable
that I suggested you set up to solve the first two questions in this note;
if you do it the way I described, the line should compile fine. 'array' is
already defined and as long as num and the other variables on that line are
all defined appropriately, you shouldn't have a compile error on that line.

Remember that you will need to be sure to concatenate the fee to that line
too. You could create the line where you are doing it now, then calculate
the fee (or charges, as you are calling it in the loop) then concatenate the
fee to the line. Or you could defer creating the line until you've finished
doing the calculation, then build the entire line, including the fee, all at
once. I'd tend to prefer the latter myself but this is pretty much a style
issue. Everyone has a different style and you will gradually evolve one too.
Any help would be very much appreciated.
This would all go much faster if I simply wrote the code for you but you're
going to learn a lot more if we reason this problem out together. I hope you
don't mind proceeding in this fashion. Simply showing you the code only
tells you WHAT you need to do; I want you to know WHY you are doing things.
 
I

IanH

Hi
I have been working on what you said. Here is my code so far. (It's
very messy at the moment, still have to clean up the comments and line
up the code. I think my problem lies with outputting the text to
screen. I followed your advice with the append method. Is my first do
loop correct?

Ian


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


outputArea.append( "Customer
Name\tAddress\tCreditCardNumber\tHours\tFee\n");

int index = 0;
index++;



do {

// convert numberOfHours to NoOfHours

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");


array[index] = name + address + creditCardNumber + hours;

} while ( name != null);



noOfHours = Integer.parseInt( hours );
double charges = calculateCharges(noOfHours);

// append original array elements to String output
for ( int counter = 0; counter < array.length; counter++ )
outputArea.append( 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
 
R

Rhino

IanH said:
Hi
I have been working on what you said. Here is my code so far. (It's
very messy at the moment, still have to clean up the comments and line
up the code. I think my problem lies with outputting the text to
screen. I followed your advice with the append method. Is my first do
loop correct?

Ian


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

outputArea.append( "Customer
Name\tAddress\tCreditCardNumber\tHours\tFee\n");
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

This isn't quite what I'd had in mind but we can use it. (I had planned to
put this header line in the array itself and then display it when we display
the array. However, there's nothing really wrong with this; it's just a
different approach that will still work.)
int index = 0;
index++;
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

You've created the variable I suggested correctly. However it isn't
appropriate to increment 'index' yet. Do you see why? If you increment
'index' now, what slot will contain the information about the first
customer? Is that the slot you want to use? What index value points at the
first slot in the array, assuming you want to start loading the array from
the beginning?
do {

// convert numberOfHours to NoOfHours

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");


array[index] = name + address + creditCardNumber + hours;

} while ( name != null);
Your loop is a lot better now but still needs some work:
1. You need to check the value of 'name' after it has a value and then, if
that value is blank, you need to skip to the end of that iteration of the
loop so that the while statement can end the loop. Do you know the statement
that will bypass the rest of the statements in an iteration of the loop?
2. You aren't calculating the fee/charges in the loop. You will want to do
that in the loop because every customer will presumably have parked a
different number of hours. Move the next two lines into the loop. Once
you've done that, you need to be sure that you write the value of the
fee/charges into the array in the same slot that contains that customer's
name, address and credit card number.
noOfHours = Integer.parseInt( hours );
double charges = calculateCharges(noOfHours);


// append original array elements to String output
for ( int counter = 0; counter < array.length; counter++ )
outputArea.append( name + "\t" + "\t" + address + "\t" +
creditCardNumber + "\t" + "\t" + hours + "\t" + charges + "\n");
//outputArea.setText( output );
Your output loop is not quite right yet. Remember, the array will already
contain all of the information about the customers and their parking by the
time you get this far. That means the output loop only has to read through
the array one slot at a time, appending the contents of that slot to the
outputArea.

If you are using a version of Java prior to Java 1.5, your output loop will
look like this:
for (int counter=0; counter<array.length; counter++)
outputArea.append(array[counter]);

If you are using Java 1.5 (or later) you have a second choice:
for (String oneLine : array)
outputArea.append(oneLine);

This second choice basically says that you want the array, with is a String
array, to be processed one slot at a time; each slot will, in turn, be
called 'oneLine' and you want to append 'oneLine' to the outputArea.
} // 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

Okay, try those changes and I think you'll see that things start to work
better.
 
I

IanH

1. When you say to bypass the statements in the do while loop, do you
mean to include an if statement, like what I have done below.

do {

// convert numberOfHours to NoOfHours

name = JOptionPane.showInputDialog("Enter your name");
if (name == "")
break;
address = JOptionPane.showInputDialog("Enter your address");
creditCardNumber = JOptionPane.showInputDialog("Enter your credit card
number");
hours = JOptionPane.showInputDialog("Enter total hours");

noOfHours = Integer.parseInt( hours );
charges = calculateCharges(noOfHours);

array[index] = name + address + creditCardNumber + charges;

} while ( name != null);

index++;

2. Will I need to change the condition of the loop from while ( name
!= null); If I will be testing it from within the while loop

Thanks for your help.
Ian.
 
R

Rhino

IanH said:
1. When you say to bypass the statements in the do while loop, do you
mean to include an if statement, like what I have done below.
Very close except that you need to change the 'if' slightly. 'name' is a
String so you need to use one of a String class method to see if the 'name'
value is blank. Use this:

if (name.equals(""))
break;
do {

// convert numberOfHours to NoOfHours

name = JOptionPane.showInputDialog("Enter your name");
if (name == "")
break;
address = JOptionPane.showInputDialog("Enter your address");
creditCardNumber = JOptionPane.showInputDialog("Enter your credit card
number");
hours = JOptionPane.showInputDialog("Enter total hours");

noOfHours = Integer.parseInt( hours );
charges = calculateCharges(noOfHours);

array[index] = name + address + creditCardNumber + charges;

} while ( name != null);

index++;

2. Will I need to change the condition of the loop from while ( name
!= null); If I will be testing it from within the while loop
I think you are asking if the while condition can be removed since you are
testing for a blank value within the loop. The answer to that question is
no; you still need to have the 'while' test. However, you will need to
change it to say:

while (!name.equals(""))
Thanks for your help.

No problem. Make these changes and try again. You're almost done....
 
I

IanH

I have made the above changes. Thanks. The program is running now but
it only outputs one record on the screen, which is the last record that
i input. have I still to work on the output for loop. This is my code
with the changes.
Ian

do {

// convert numberOfHours to NoOfHours

name = JOptionPane.showInputDialog("Enter your name");
if (name.equals(""))
break;
address = JOptionPane.showInputDialog("Enter your address");
creditCardNumber = JOptionPane.showInputDialog("Enter your credit card
number");
hours = JOptionPane.showInputDialog("Enter total hours");

noOfHours = Integer.parseInt( hours );
charges = calculateCharges(noOfHours);

array[index] = name + "\t" + "\t" + address +"\t" +
creditCardNumber + "\t" + "\t" + hours + "\t" + charges + "\n";


} while (!name.equals(""));

index++;

for (int counter=0; counter<array.length; counter++)
outputArea.append(array[counter]);
 
R

Rhino

IanH said:
I have made the above changes. Thanks. The program is running now but
it only outputs one record on the screen, which is the last record that
i input. have I still to work on the output for loop. This is my code
with the changes.
Ian

The current position of the statement that increments the index, which is
outside the loop, ensures that you are only going to increment it once;
that's your problem. Each new line of the array clobbers the previous one so
you only ever see the last customer that was entered.

Just move 'index++;' so that it follows the 'array[index] = ...' statement
and is still within the loop. That will ensure that the index gets
incremented after EVERY line is added to the array.

--

Just as a general remark, if you don't have a debugger, you should think
about getting one. They come standard with most IDEs; certainly Eclipse, the
IDE I use, has a good debugger. This tool will let you watch your program
execute one line at a time so that you can see what happens at each step
along the way. It's a very good way of learning what is going on within your
program and exactly what happens when. Then, if a program is misbehaving,
you can see exactly what it is doing and figure out how to change it to make
it behave correctly.

Getting a debugger (or an IDE with a debugger) is probably not worth the
bother if you are only going to take one course and never touch Java again
but if you plan on getting serious about Java (or any other programming
language for that matter), I think a debugger for that language is a good
way to help you understand how the language works.
 
I

IanH

Sorry to bother you again, but if i wanted to create a running total
after filling the array would i create another array or is it possible
to calcualate the total of all charges.

Ian.
 
I

IanH

I need to include a running total in the following array. I have
attempted it but I went wrong somewhere but not sure where. Any help
would be appreciated.
Ian


//Java Packages
import java.awt.Container;
import javax.swing.*;

public class test extends JApplet {

// initialize applet by obtaining values from user and storing them
in an array
public void init()
{

String name;
String address;
String creditCardNumber;
String hours;
int noOfHours; // noOfHours used to convert string hours to
integer
double charges; // Used to pass the charge calcualted in the
method calculateCharges
double runningTotal;

String customerArray[]; //declared array
customerArray = new String[ 20 ]; //create array



JTextArea outputArea = new JTextArea(); // create JTextArea to
display outputArea
Container container = getContentPane(); // creates the interface
container.add( outputArea ); // outputArea is placed on the
interface

// set the first line of text in the outputArea
outputArea.append( "Left Luggage Department\n Galway Railway
Station\n Customer Charges\n" + "\n" +
"Customer
Name\tAddress\tCreditCardNumber\tHours\tFee\n");

// initialise integer to increment each record to the array
int index = 0;
double total = 0;

do {
// get user input to be stored in the array
name = JOptionPane.showInputDialog("Enter your name");
// check if name is null to break out of the loop
if (name.equals(""))
break;
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 );

// call calculateCharges to calculate the fee
charges = calculateCharges(noOfHours);

runningTotal = sum(charges[customerArray]);
//fill array and position the records
customerArray[index] = name + "\t" + "\t" + address
+"\t" + creditCardNumber + "\t"
+ "\t" + hours + "\t" + charges +
"\n" + runningTotal;
//secondarray[total] = charges;

// add record to the array
index++;

// loop while name is not empty
} while (!name.equals(""));



// loop through the array elements and output the records
for (int counter=0; counter<customerArray.length;
counter++)
// append the outputArea to include the elements in the
array
outputArea.append(customerArray[counter]);



//outputArea.append("running total" + total);
} // end method init

// check calcualtion again
// method to calculate the charges due
public double calculateCharges(int hoursParked) {

// initialise variables
double fee = 0.00;
int NoOfHours = 0;

if ( hoursParked >=24 )
fee = 10.00;
else if ( hoursParked > 3)
fee = (hoursParked - 3 ) * .5 + 2.00;
else if ( hoursParked <= 3)
fee = 2.00;
return fee;

}// end method calculateCharges

//int arraylength = <numbers>.length;
public double sum(double [] numbers)
{
double total =0;

for (int i =0; i<numbers.length; i++) {
total += numbers;
}
return total;
}

} // end class customerCharges
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top