Gabriel O Figueroa
Gabriel O Figueroa

Reputation: 21

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!

Upvotes: 2

Views: 1514

Answers (7)

Terry Li
Terry Li

Reputation: 17268

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.

Upvotes: 0

nick
nick

Reputation: 2853

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.

Upvotes: 0

ObedMarsh
ObedMarsh

Reputation: 433

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.

Upvotes: 0

Eng.Fouad
Eng.Fouad

Reputation: 117647

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

Upvotes: 7

Quirin
Quirin

Reputation: 738

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

Upvotes: 0

PeakGen
PeakGen

Reputation: 23035

Two ways.

  1. 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);
}

**

Upvotes: 0

Shelef
Shelef

Reputation: 3827

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

Upvotes: 1

Related Questions