Reading from CSV file and create object - java

I'm a complete beginner to Java and I have been given an exercise where I have to read data from a CSV file and then create an object for each line of the file as the program reads the data from the file.
Here is part of the CSV file:
1,Jay, Walker,91 Boland Drive,BAGOTVILLE,NSW,2477
2,Mel, Lowe,45 Ocean Drive,MILLERS POINT,NSW,2000
3,Hugh, Manatee,32 Edgecliff Road,REDFERN,NSW,2016
4,Elizabeth, Turner,93 Webb Road,MOUNT HUTTON,NSW,2290
and so on ...
Here is my code that reads data from the CSV file:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Client_19918424 {
public static void main(String[] args) throws FileNotFoundException {
File inFile = new File("clients.txt");
Scanner inputFile = new Scanner(inFile);
String str;
String[] tokens;
while (inputFile.hasNext()) {
str = inputFile.nextLine(); // read a line of text from the file
tokens = str.split(","); // split the line using commas as delimiter
System.out.println("Client ID: " + tokens[0]);
System.out.println("Client First Name: " + tokens[1]);
System.out.println("Client Sur Name: " + tokens[2]);
System.out.println("Street Address: " + tokens[3]);
System.out.println("Suburb: " + tokens[4]);
System.out.println("State: " + tokens[5]);
System.out.println("Postcode:" + tokens[6]);
System.out.println( );
} // end while
}
}
this is my Client class (have constructor):
public class Client {
private int clientID;
private String firstName;
private String surName;
private String street;
private String suburb;
private String state;
private int postcode;
// constructor
public Client (int ID, String fName, String sName, String str, String sb, String sta, int pCode) {
clientID = ID;
firstName = fName;
surName = sName;
street = str;
suburb = sb;
state = sta;
postcode = pCode;
}
However I don't know how to create a Client object for each line of text file as the program reads data from file.
like for the first line make something like this:
Client client1 = new Client(1, "Jay", "Walker", "91 Boland Drive", "BAGOTVILLE", "NSW", 2477);
And then add it to array:
Client[0] = client1;
can someone help me to solve this question, im really appreciate.

You are almost there.
All that's left to do is to map each token that is already printed to the corresponding fields in the Client class. Since token[0] doesn't really tell what value it holds you could do it in three ways:
while (inputFile.hasNext()) {
str = inputFile.nextLine();
tokens = str.split(",");
// Because tokens[0] is of type String but clientID is of type int,
// we need to parse it and get the integer representation.
int clientID = Integer.parseInt(tokens[0]);
// Both of type String, no parsing required.
String firstName = tokens[1];
String surName = tokens[2];
String street = tokens[3];
String suburb = tokens[4];
String state = tokens[5];
int postcode = Integer.parseInt(tokens[6]);
// Then all that's left to do is to create a new object of `Client` type
// and pass all the gathered information.
Client client = new Client(clientID, firstName, surName, street, suburb, state, postcode);
System.out.println(client + "\n");
}
At this moment if we try to print the client (last line) we will get something like this: com.example.demo.Client#30a3107a. That's because we didn't tell how we want our object to be displayed. For that toString() method in Client class has to be overriden like so:
#Override
public String toString() {
return "Client ID: " + clientID + "\n" + "Client First Name: " + firstName + "\n"
+ "Client Sur Name: " + surName + "\n" + "Street Address: " + street + "\n"
+ "Suburb: " + suburb + "\n" + "State: " + state + "\n" + "Postcode: " + postcode;
}
It will give the exact output that is in your example.
It is achievable to create the class by passing those tokens directly as well, without the creation of temporary variables:
Client client = new Client(Integer.parseInt(tokens[0]), tokens[1], tokens[2], tokens[3], tokens[4], tokens[5], Integer.parseInt(tokens[6]));
This case brings us to the third solution with setters and getters.
The variables that describe the Client are already defined, it is possible to pass them to assemble the perfect object, but it is not possible to retrieve them. Instead of setting the variables directly in the constructor, we can create a special method that will do the job, for instance:
// Other fields omitted
private int clientID;
// The empty constructor required for later usage,
// since right now, we can't create the object without specifying every property.
public Client() {
}
// This method does exactly the same thing that was done before but
// in the constructor directly
public void setClientID(int clientID) {
this.clientID = clientID;
}
// This method will assist in retrieving the set data from above.
public int getClientID() {
return clientID;
}
And then the while loop would look like this instead:
Client client = new Client();
client.setClientID(Integer.parseInt(tokens[0]));
client.setFirstName(tokens[1]);
client.setSurName(tokens[2]);
client.setStreet(tokens[3]);
client.setSuburb(tokens[4]);
client.setState(tokens[5]);
client.setPostcode(Integer.parseInt(tokens[6]));
And to get those values:
System.out.println("Client ID: " + client.getClientID());
Or you could use the constructor with the fields to create the client, add getters in the class, omit both setters, and the empty constructor if the creation of the client should only be possible with all the fields present.

Related

Why do I get, and how do I solve this "String to object of type <objecttype>" error

I am (being an absolute beginner), trying to create a simple tool, that creates some objects and links them.
The objects are:
Customers
Licenses (2 types, extends class)
The idea is to use (one of) the customer company name when creating a license, so the license is linked to a customer.
I use ArrayLists to store the data.
I tried to use the getter for Customer cCompany, but when I try to actually create a new license object, I get errors about incompatible types (String to object of type customer)
How can I fix that error?
Any help is highly appreciated, but please explain well, me being an absolute beginner. I probably overcomplicate stuff....
Some code extracts:
From Main:
public class Main {
public static void main(String[] args) {
//Create customers
List <Customer> customers = new ArrayList <> (10);
customers.add(new Customer("TestCompany","John Doe",1234567890,"John#testcompany.com"));
....
//Create Elvis licenses (based on superclass License)
List <ElvisLicense> ellicenses = new ArrayList <> (10);
ellicenses.add(new ElvisLicense("TestCompany","VendorA",1234,"1234-A","Solutions Server gold","1234-dtbk-87654-nlof",10, true , true));
Class: Customer:
class Customer {
String cCompany;
private String cName;
private int cPhone;
private String cEmail;
public Customer( String cCompany, String cName,int cPhone, String cEmail)
{
this.cCompany = cCompany;
this.cName = cName;
this.cPhone = cPhone;
this.cEmail = cEmail;
}
//This getter should be used to link the license to the customer (Done in License.java)
public String getcCompany() {
return cCompany;
}
Class License (Superclass)
class License {
// Used no modifier to set access for Class/Package and Subclass inside the package
Customer licenseCompany;
String lVendor;
int lContractNumber;
String lCertificateNumber;
String lProductName;
String lLicenseKey;
int lNumberOfSeats;
public License(Customer cCompany, String lVendor, int lContractNumber, String lCertificateNumber,
String lProductName, String lLicenseKey, int lNumberOfSeats)
{
licenseCompany = cCompany;
this.lVendor = lVendor;
this.lVendor = lVendor;
this.lContractNumber = lContractNumber;
this.lCertificateNumber = lCertificateNumber;
this.lProductName = lProductName;
this.lLicenseKey = lLicenseKey;
this.lNumberOfSeats = lNumberOfSeats;
}
public Customer getLicenseCompany() {
return licenseCompany;
}
public void setLicenseCompany(Customer licenseCompany) {
this.licenseCompany = licenseCompany;
}
//preparations to allow for example printing the content of an arraylist element
#Override
public String toString(){
return "Customer name " + getLicenseCompany() + "\n" + "Vendor name " + getlVendor() + "\n" + "Contract number: " + getlContractNumber() + "\n"
+ "Certificate number: " + getlCertificateNumber() + "\n" +
"Product name " + getlProductName() + "\n" + "Licence key: " + getlLicenseKey() + "\n"
+ "Number of seats: " + getlNumberOfSeats();
}
}
And the extended class:
public class ElvisLicense extends License{
private boolean elIsBundle;
private boolean elIsSubscription;
public ElvisLicense(
Customer licenseCompany,
String lVendor,
int lContractNumber,
String lCertificateNumber,
String lProductName,
String lLicenseKey,
int lNumberOfSeats,
boolean elIsBundle,
boolean elIsSubscription
)
{
super(
licenseCompany,
lVendor,
lContractNumber,
lCertificateNumber,
lProductName,
lLicenseKey,
lNumberOfSeats);
this.elIsBundle = elIsBundle;
this.elIsSubscription = elIsSubscription;
}
.....
#Override
public String toString(){
return "Customer name " + licenseCompany + "\n"
+ "Vendor name " + lVendor + "\n"
+ "Contract number: " + lContractNumber + "\n"
+ "Certificate number: " + lCertificateNumber + "\n"
+ "Product name " + lProductName + "\n"
+ "Licence key: " + lLicenseKey + "\n"
+ "Number of seats: " + lNumberOfSeats + "\n"
+ "Number of seats: " + elIsBundle + "\n"
+ "Number of seats: " + elIsSubscription;
}
}
I expect that the Customername is used when creating a new license.
Below line is wrong.
ellicenses.add(new ElvisLicense("TestCompany","VendorA",1234,"1234-A","Solutions Server gold","1234-dtbk-87654-nlof",10, true , true));
As license need customer object an parameter. Instead, you should create customer object first.
ellicenses.add(new ElvisLicense(new Customer("TestCompany","VendorA",1234,"1234-A"),"Solutions Server gold","1234-dtbk-87654-nlof",10, true , true));
for reusing that customer list to avoid create company.
for(Customer customer : customers){
// here you need some way to offer other parameters except customer parameter.
License license = new new ElvisLicense(customer,"Solutions Server gold","1234-dtbk-87654-nlof",10, true , true);
ellicenses.add(license);
}
What you need to do is to use one of the Customer objects you have already created when creating the ElvisLicense object. To more easily find that customer by name I suggest you store them in a map instead of a list with the name as a key.
Map<String, Customer> customerMap = new HashMap<>();
Customer customer = new Customer("TestCompany","John Doe",1234567890,"John#testcompany.com"));
customerMap.put(customer.getcCompany(), customer);
so when creating the license you look up the customer
List <ElvisLicense> ellicenses = new ArrayList <> (10);
Customer customer = customerMap.get("TestCompany");
if (customer != null) {
ElvisLicense license = new ElvisLicense(customer,"VendorA",1234,"1234-A","Solutions Server gold","1234-dtbk-87654-nlof",10, true , true));
ellicenses.add(license);
} else {
//If the customer isn't found you need some kind of error handling, better than below :)
System.out.println("Can't create a license, no customer found");
}

OpenCSV flat to hierarchy structure data parsing

I need advice on the issue which I am facing while parsing CSV data in java.
I have a CSV file with data in below format
name, gender, address_first_line, address_second_line, city, number
me, Male, anonymous, random, Auckland, 6545
other, Female, random, anon, Auckland, 6688
I want to parse the CSV file using the openCSV library in below Object Model. I am aware of parsing single class but facing issues while parsing data when multiple classes are involved. Please suggest if there is any other library available which can help me to get the desired result.
Class User {
String name;
String gender;
Address address;
long number;
}
Class Address {
String firstLine;
String secondLine;
}
univocity-parsers has a #Nested annotation you can use:
Try this:
public static class User {
#Parsed
String name;
#Parsed
String gender;
#Nested
Address address;
#Parsed
long number;
#Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", gender='" + gender + '\'' +
", address=" + address +
", number=" + number +
'}';
}
}
public static class Address {
#Parsed(field = "address_first_line")
String firstLine;
#Parsed(field = "address_second_line")
String secondLine;
#Override
public String toString() {
return "Address{" +
"firstLine='" + firstLine + '\'' +
", secondLine='" + secondLine + '\'' +
'}';
}
}
public static void main(String ... args){
StringReader input = new StringReader(
"name,gender,address_first_line,address_second_line, city,number\n" +
"John,M,Somewhere,Else,City,1");
for(User user : new CsvRoutines().iterate(User.class, input)){
System.out.println(user.toString());
}
}
Output:
User{name='John', gender='M', address=Address{firstLine='Somewhere', secondLine='Else'}, number=1}
If you don't like annotations you can map things manually:
CsvRoutines routines = new CsvRoutines();
ColumnMapper mapper = routines.getColumnMapper();
mapper.attributeToColumnName("name", "name");
mapper.attributeToColumnName("gender", "gender");
mapper.attributeToColumnName("number", "number");
mapper.attributeToColumnName("address.firstLine", "address_first_line");
mapper.attributeToColumnName("address.secondLine", "address_second_line");
for (User user : routines.iterate(User.class, input)) {
System.out.println(user.toString());
}
Hope it helps.
Disclaimer: I'm the author of this lib. It's open-source and free (Apache 2.0 license)

Reading Files to Store their Data in an Array

The program that I am writing is in Java.
I am attempting to make my program read the file "name.txt" and store the values of the text file in an array.
So far I am using a text file that will be read in my main program, a service class called People.java which will be used as a template for my program, and my main program called Names.java which will read the text file and store its values into an array.
name.txt:
John!Doe
Jane!Doe
Mike!Smith
John!Smith
George!Smith
People.java:
public class People
{
String firstname = " ";
String lastname = " ";
public People()
{
firstname = "First Name";
lastname = "Last Name";
}
public People(String firnam, String lasnam)
{
firstname = firnam;
lastname = lasnam;
}
}
Names.java:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Names
{
public static void main(String[]args)
{
String a = " ";
String b = "empty";
String c = "empty";
int counter = 0;
People[]peoplearray=new People[5];
try
{
File names = new File("name.txt");
Scanner read = new Scanner(names);
while(read.hasNext())
{
a = read.next();
StringTokenizer token = new StringTokenizer("!", a);
while(token.hasMoreTokens())
{
b = token.nextToken();
c = token.nextToken();
}
People p = new People(b,c);
peoplearray[counter]=p;
++counter;
}
}
catch(IOException ioe1)
{
System.out.println("There was a problem reading the file.");
}
System.out.println(peoplearray[0]);
}
}
As I show in my program, I tried to print the value of peoplearray[0], but when I do this, my output reads: "empty empty" which are the values I gave String b and String c when I instantiated them.
If the program were working corrrectly, the value of peoplearray[0] should be, "John Doe" as those are the appropriate values in "names.txt"
What can I do to fix this problem?
Thanks!
StringTokenizer(String str, String delim)
is the constructor of StringTokenizer.
You have written it wrong .
Just change your line
StringTokenizer token = new StringTokenizer("!", a); to
StringTokenizer token = new StringTokenizer(a, "!");
Just change it a little bit
StringTokenizer token = new StringTokenizer(a, "!");
while(token.hasMoreTokens())
{
b = token.nextToken();
c = token.nextToken();
}
//do something with them

Reading a records file and create a index for it

So I need to read from a records file where '#' determines the end of a record and '|' the end of a field like this: #9783642217074|Interaction|Macie|Furtado,Elizabeth|Winckler,Marco|2011#.
Then I need to write just the first field of each record in another file.
I'm trying to use Java I/O RandomAccessFile but I really need some light to figure it out.
If anyone could tell what methods or the ideia behind this Ill be thankful.
You do not need RandomAccessFile, you would be fine with reading and writing your files character-by-character.
Your program can be in any of these three states:
Waiting for the start of the next record
Writing the content of the first field
Waiting for the end of the record
The program changes its state as follows:
Initially, it is in the state number 1
When # character is detected in state 1, the state becomes 2
When | is detected in state 2, the state becomes 3
When # is detected in state 3, the state becomes 1.
Each character received in state 2 is duplicated into the output file
When the state transitions from 3 to 1, write a separator into the output.
This should be really straightforward to code with a single loop that reads from a file, and a handful of if-then-else statements. Make a variable called state outside the loop, set it to 1, open the input and the output files, and make a loop to read the input character-by-character until the end of the file is reached.
Here is an implementation using the Scanner class.
Main.class
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
// The path of the project
String basePath = new File("").getAbsolutePath();
// The path of the record file, in relevance to <basePath>
String recordPath = basePath.concat("/RecordList.txt");
// Make sure that path is correct
System.out.println(recordPath + "\n");
// Store all Record objects in an array
ArrayList<Record> recordArray = new ArrayList<Record>();
// Lets try to read the file, and parse each line at a time
try {
// input the file content to the String "input"
BufferedReader file = new BufferedReader(new FileReader(recordPath));
// Store every line of <file> in <input> String
String line;
String input = "";
while ((line = file.readLine()) != null) {
input += line + '\n';
// Remove the # symbols at beginning and end
line = line.replaceFirst("#", "");
System.out.println(line);
//
String recordData[] = line.split("[|]");
Record record = new Record(recordData);
recordArray.add(record);
}
// Make sure to close the <file>
file.close();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println();
//Verify results
for (Record record : recordArray) {
System.out.println(record.toString());
}
}
}
Record.class
public class Record {
// #9783642217074|Interaction|Macie|Furtado,Elizabeth|Winckler,Marco|2011#
private String id;
private String field2;
private String field3;
private String field4;
private String field5;
private String year;
public Record(String[] recordData) {
this.id = recordData[0];
this.field2 = recordData[1];
this.field3 = recordData[2];
this.field4 = recordData[3];
this.field5 = recordData[4];
this.year = recordData[5];
}
/* (non-Javadoc)
* #see java.lang.Object#toString()
*/
#Override
public String toString() {
return "Record [id=" + id + ", field2=" + field2 + ", field3="
+ field3 + ", field4=" + field4 + ", field5=" + field5
+ ", year=" + year + "]";
}
}
And here is the RecordFile.txt I generated (mind the data I made up)
#9783642217074|Interaction|Macie|Furtado,Elizabeth|Winckler,Marco|2011#
#9783612343243|Interaction|Freddie|Fuder,Franscon|Winner,Marie|2013#
#9213432423534|Interaction|Jimbo|Furtado,Melo|Yakasabi,Johnson|2001#
As always, please use my code as a reference. It is always better to learn how to write code yourself, especially when this question pertains to a homework assignment.

Need help creating multiple return statements in a java methood

I'm a freshmen at college and I'm starting with my first Java programming course. The professor sent us an assignment in order to make an application simulating the database of the USPS.
Anyways, I got to the point where I want my program to ask line by line for the recipients information (address, name, city etc) and I managed to do so using a simple JOptionPane. The problem is that now, I'm using Java methods and I can't for the life of me figure out how to make the return statement so my program moves on to the next method, with my recipients information.
private static String getString(String string) {
// TODO Auto-generated method stub
String nameString = JOptionPane.showInputDialog(null,
"Recipients name:", "Certified Mail Receipt", 3);
String streetAddressString = JOptionPane.showInputDialog(null,
"Street, Apt. No. or P.O. Box No.:", "Certified Mail Receipt",
3);
String cityString = JOptionPane.showInputDialog(null,
"City, State, Zip Code", "Certified Mail Receipt", 3);
// return ?????????`
}
The compiler will only let me insert one return statement and only one of the 3 questions gets sent to the next methood. I think I need a way to get the three things in a return statement so the program stops asking the same recipients information questions over and over again.
I'm using the Eclipse Java compiler if that helps. Thanks!
======================EDIT================================
#TerryLi helped me by finding an error in my class
private static String getString(String type) {
String result = JOptionPane.showInputDialog(null,
type,
"Certified Mail Receipt",
3);
return result;
}
This is how I manged to get it to work. again thanks to #terryli and everyone who helped out with a reply!
Write a wrapper class that holds the data:
public class SomeWrapper
{
private String name;
private String address;
private String city;
public SomeWrapper(String n, String a, String c)
{
name = n;
address = a;
city = c;
}
public String getAddress(){return address;}
public String getName(){return name;}
public String getCity(){return city;}
}
Then use it like:
private static String getData()
{
// ...
SomeWrapper w = new SomeWrapper(nameString, streetAddressString, cityString);
return w;
}
and extract it like this:
SomeWrapper w = getData();
String nameString = w.getName();
String streetAddressString = w.getAddress();
String cityString = w.getCity();
You can use array or static variables outside this method.
a method can easily returns array of string that containt all the three strings you hava been prompted
Let me provide an alternative:
String splitter = "-.-";
return nameString+splitter+streetAddressString+splitter+cityString;
We can retrieve the return values as follows:
String returns = getString(...);
String nameString = returns.split(splitter)[0];
String streetAddressString = returns.split(splitter)[1];
String cityString = returns.split(splitter)[2];
And this would be the only workaround in case you want to keep the method signature the same.
Edit:
Given that you are new to Java, try the following code:
return nameString+"-.-"+streetAddressString+"-.-"+cityString;
Basically, I just removed the global variable splitter to make it simple for you.
String nameString = returns.split("-.-")[0];
String streetAddressString = returns.split("-.-")[1];
String cityString = returns.split("-.-")[2];
Update:
You only need to modify the getString method as follows:
private static String getString(String type) {
String result = JOptionPane.showInputDialog(null,
type,
"Certified Mail Receipt",
3);
return result;
}
This should solve your problem. Let me know.
Update2:
private static void showReceipt(double postage, double certifiedFee,
double restrictedFee, double returnReceiptFee, String nameString,
String addressString, String cityString) {
// TODO Auto-generated method stub
DecimalFormat fmt = new DecimalFormat(" $0.00");
double certifiedMailFee = 0;
double restrictedDelivery = 0;
String outputString = "U.S. POSTAL SERVICE\nCERTIFIED MAIL RECEIPT\n---------------------\nPostage" +
fmt.format(postage) +
"\nCertified Mail Fee" + fmt.format(certifiedMailFee) +
"\nRestricted Delivery Fee" + fmt.format(restrictedDelivery) +
"\nReturn Receipt Fee" + fmt.format(returnReceiptFee) +
"\nTotal Postage & Fees" + fmt.format(postage + certifiedMailFee + restrictedDelivery + returnReceiptFee) +
"\n----------------------------" +
"\nSend to:" +
"\n" + nameString +
"\n----------------------------" +
"\nStreet, Apt No., or PO Box No." +
"\n" + addressString +
"\n----------------------------" +
"\nCity, State, ZIP+4®" +
"\n" + cityString;
JOptionPane.showMessageDialog(null,
outputString,
"Certified Mail Receipt",
1,
null);
}
Hopefully, you will notice the change I just made to the code above.
Two ways.
Use Global Varaibles
**
**
**
private static String nameString, streetAddressString, cityString;
private static String getString(String string) {
// TODO Auto-generated method stub
nameString = JOptionPane.showInputDialog(null,
"Recipients name:", "Certified Mail Receipt", 3);
streetAddressString = JOptionPane.showInputDialog(null,
"Street, Apt. No. or P.O. Box No.:", "Certified Mail Receipt",
3);
cityString = JOptionPane.showInputDialog(null,
"City, State, Zip Code", "Certified Mail Receipt", 3);
//No need to return, they are available globally
}
**
**
**
OR, Pass them as method parameters
**
private static String getString(String string) {
// TODO Auto-generated method stub
String nameString = JOptionPane.showInputDialog(null,
"Recipients name:", "Certified Mail Receipt", 3);
String streetAddressString = JOptionPane.showInputDialog(null,
"Street, Apt. No. or P.O. Box No.:", "Certified Mail Receipt",
3);
String cityString = JOptionPane.showInputDialog(null,
"City, State, Zip Code", "Certified Mail Receipt", 3);
stringMethod(nameString,streetAddressString,cityString);
}
**
The Java programming language doesn't allow to return multiple variables. But you can return objects, most precisely, you can return a reference to an object. So, if you want to return multiple things, just create a data structure (class) that fits all of your requirements, and return a instance of it.
E.g.:
public class DataStruct{
public DataStruct(String nameString, String streetAddressString, String cityString){
this.nameString = nameString;
this.streetAddressString = streetAddressString;
this.cityString = cityString;
}
public String nameString;
public String streetAddressString;
public String cityString;
}
private static String getString(String string) {
// TODO Auto-generated method stub
String nameString = JOptionPane.showInputDialog(null,
"Recipients name:", "Certified Mail Receipt", 3);
String streetAddressString = JOptionPane.showInputDialog(null,
"Street, Apt. No. or P.O. Box No.:", "Certified Mail Receipt",
3);
String cityString = JOptionPane.showInputDialog(null,
"City, State, Zip Code", "Certified Mail Receipt", 3);
return new DataStruct(nameString,streetAddressString,cityString);
}
In my humble opinion you have two obvious options, depending on how you wanna use the strings afterwards. The way I see it, you could either return a concatenated string that returns all the information from all the variables, which would be made like this in your case:
/* The \n just puts each peace of info on a new line you could just do a
" " instead or something. */
return nameString+"\n"+streetAddressString+"\n"+cityString;
Or you could return a stringarray with each string in a certain place(index):
String[] stringList = new String[3];
And read them into the array and return the array (don't forget to change the return type if you do this).
/* index in arrays start at 0 so its always 1 less than the size you make it
(if you didnt know) */
stringList[0] = nameString;
stringList.... etc.
Also you should know that getters are usually public classes, you simply make the field values private and get them with the getters. (as standard practice and as far as I know anyways).
Hope it helps.
EDIT: In my opinion using static variables when it's not even necessary, is a very bad idea. If you can solve the problem without it, do it that way instead.
Java won't allow you to return multiple values unless you use either an array or a wrapper class or structure of some kind. Since both those approaches have been covered already, I would suggest the alternative of splitting it up into a few different methods to make it more readable.
private static String promptForString(String message, String title)
{
return JOptionPane.showInputDialog(null,message,title,3);
}
private static String promptForName()
{
return promptForString("Recipients name:","Certified Mail Receipt");
}
private static String promptForStreetAddress()
{
return promptForString("Street, Apt. No. or P.O. Box No.:","Certified Mail Receipt");
}
private static String promptForCity()
{
return promptForString("City, State, Zip Code","Certified Mail Receipt");
}
then in your caller method you could simply use
String name = promptForName();
String streetAddress = promptForStreetAddress();
String city = promptForCity();
This has the added advantage of allowing you to add more fields fairly easily or using the promptForString method for something else altogether.

Categories