Question

So, I haven't done any programming in a few months because I'm taking general prerequisite courses right now and I have a job, so now I'm a little rusty and I'd like to be up to par for when I take my next programming class in the Fall. Long story short, I'm trying to get back on track, so I'm making a silly practice program.

I made this program with all input and output done through the console using a Scanner, but then decided to go ahead and move over to JOptionPane as an interface. It was a pretty easy transition overall, but I'm just having a problem with the output at the very end. I'm trying to make all of the elements of an array into a nice, grammatically correct String for easy output in JOptionPane, but I can't really get my concatenation to work correctly. I realize that the output is not grammatically accurate when the amount of cats is one or two. I'll work on that after this, it's an easy fix.

Here is the code:

import javax.swing.JOptionPane;

public class JavaTestClass {
public static void main(String[] args)
{   
    //Get number of cats
    int numOfCats = Integer.parseInt(JOptionPane.showInputDialog("How many cats do you have?"));
    JOptionPane.showMessageDialog(null, "Oh, so you have " + numOfCats + " cats.\n", "Confirmation", JOptionPane.INFORMATION_MESSAGE);

    //Get cat's names
    String[] catNames = new String[numOfCats]; 
    for(int i=0;i<numOfCats;i++)
    {
        catNames[i] = JOptionPane.showInputDialog("Enter the name of cat " + (i+1) + ": ");
    }

    //Output cat's names
    String catNameList = null;
    for(int i=0;i<numOfCats;i++)
    {
        if((i+1) == (numOfCats-1))
        {
            catNameList.concat(catNames[i] + ", and ");
        }
        else if ((i+1) == numOfCats)
        {
            catNameList.concat(catNames[i] + ".");
        }
        else
        {
            catNameList.concat(catNames[i] + ", ");
        }
    }
    JOptionPane.showMessageDialog(null, "So your cat's names are: " + catNameList, "Names of cats", JOptionPane.INFORMATION_MESSAGE);
}
}

Sorry about the spacing. It didn't really come out the way I wanted it to on here, but I don't have all day the indent all of the lines just for the sake of the post. Anyway, it should be relatively obvious, even without my long description above what I'm trying to do. Any help would be much appreciated. Thanks in advance.

Was it helpful?

Solution

Strings are immutable. Every operation that modifies a String returns a new one.

So it should be:

catNameList = catNameList.concat(catNames[i] + ", and ");

Also don't initialize it to null.

String catNameList = "";

OTHER TIPS

Reference the String concat javadoc. Concat method is returning the result of concatenation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top