问题
This is what I have so far. What this program basically does is take user input(their social security numbers), verifies that their input is in the proper format (XXX-XX-XXXX), adds the verified input to the arrays list. Now the final step is to create a toString() method that will return a human readable String representation of all social security numbers added to the array. This method must use a for loop, and must print 1 social security number entry per line. For example:
"The Social Security Numbers you entered are:
345-43-5674
456-62-8435
910-70-0053"
package SSNServerStorage;
public class SSNArray
{
private String[] SSNNumber;
private int arrayCount;
public SSNArray(){
SSNNumber = new String[300];
arrayCount = 0;
}
public SSNArray(int arraySize){
SSNNumber = new String[arraySize];
arrayCount = 0;
}
public String[] getSSNNumber(){
return SSNNumber;
}
public int getArrayCount(){
return arrayCount;
}
public boolean validateSSNNumber(String SSNFormat){
return SSNFormat.matches("\\d{3}-\\d{2}-\\d{4}");
}
public String addSSN(String SSNFormat){
if (validateSSNNumber(SSNFormat)){
return SSNNumber[arrayCount++] = SSNFormat;
}else{
return null;
}
}
public String toString(){
System.out.println("The Social Security Numbers you entered are:");
for()
{
//
//
//
//
}
}
}
回答1:
You can declare a String
to concatenate all the SSNumbers.
@Override
public String toString(){
String str = "The Social Security Numbers you entered are:\n";
for(int x=0; x< arrayCount; x++)
str += SSNumber[x] + "\n";
return str;
}
Since it is a toString()
method, you will want to return the string representation of the class instead of doing println()
.
回答2:
Your toString
method doesn't have correct signature, it should return String
. This should do what you need:
@Override
public String toString(){
StringBuilder sb = new StringBuilder("The Social Security Numbers you entered are:\n");
for (int i = 0; i < arrayCount; i++) {
sb.append(SSNNumber[i]).append("\n");
}
return sb.toString();
}
Also remember to use the @Override
annotation.
回答3:
Just concatenate :
@Override
public String toString(){
String s = "The Social Security Numbers you entered are:\n";
for(int i =0; i < SSNNumber.length; i ++)
s +=SSNNumber[i]+"\n";
return s;
}
回答4:
StringBuilder strbul = new StringBuilder()
for(int i=0;i<SSNNumber.length;i++)
{
strbul.append(SSNNumber[i]).append("\n");
}
return strbul.toString();
来源:https://stackoverflow.com/questions/32787238/return-multiple-arrays-using-for-loop-inside-tostring-class