java - String concatenation in relation to JOptionPane -
so, haven't done programming in few months because i'm taking general prerequisite courses right , have job, i'm little rusty , i'd par when take next programming class in fall. long story short, i'm trying on track, i'm making silly practice program.
i made program input , output done through console using scanner, decided go ahead , move on joptionpane interface. pretty easy transition overall, i'm having problem output @ end. i'm trying make of elements of array nice, grammatically correct string easy output in joptionpane, can't concatenation work correctly. realize output not grammatically accurate when amount of cats 1 or two. i'll work on after this, it's easy fix.
here 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 have?")); joptionpane.showmessagedialog(null, "oh, 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 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] + ", , "); } else if ((i+1) == numofcats) { catnamelist.concat(catnames[i] + "."); } else { catnamelist.concat(catnames[i] + ", "); } } joptionpane.showmessagedialog(null, "so cat's names are: " + catnamelist, "names of cats", joptionpane.information_message); } } sorry spacing. didn't come out way wanted on here, don't have day indent of lines sake of post. anyway, should relatively obvious, without long description above i'm trying do. appreciated. in advance.
strings immutable. every operation modifies string returns new one.
so should be:
catnamelist = catnamelist.concat(catnames[i] + ", , "); also don't initialize null.
string catnamelist = "";
Comments
Post a Comment