¿Cómo usar correctamente String.format con 2 fuentes de matriz entrantes diferentes?

i wish to know the best way to use String.format in this case...

String names[] = new String[10];
int idNumber[] = new int[10];
String list = "";

for( byte pos = 0; pos < idNumber.length; pos++){
names[pos] = JOptionPane.showInputDialog("Enter the name...");
idNumber[pos] = Integer.parseInt(JOptionPane.showInputDialog("Enther the ID number..."));
list += ("Name: " + names[pos] + "ID: " + idNumber + "\n");
JOptionPane.showMessagedialog(null, list);

I wish to use the String.format to change the output of "list"


 Name: John Wilson ID: 56
 Name: Edward Sinclair ID: 60
 Name: Bob Stuart ID: 77


 Name: John Wilson     ID: 56
 Name: Edward Sinclair ID: 60
 Name: Bob Stuart      ID: 77

how do i properly use the %-10s... %-5s... in this case ? im a little lost here... thanks in advance.

preguntado el 26 de agosto de 12 a las 23:08

There is no difference between your from and to examples? Also, on a side note, use StringBuilder instead of concatenating to a string via +=. -

Tu has declarado idNumber as an array yet you're using it as an integer! -

@vulcan: the difference is the whitespace -

sorry Eric i will fix this, thanks -

Missed one, in the string concatenation line -

1 Respuestas

I really don't see what you were having problems with using string.format. Did you actually try it?

list += ("Name: %20s ID: %02d\n").format(names[pos], idNumber[pos]);

As mentioned, it would be more efficient to have:

StringBuilder list = new StringBuilder();

Y luego reemplazar list += ... con list.append(...)

Respondido 26 ago 12, 23:08

I recommend using StringBuilder instead of using += to append one string to another. It improves efficiency to do so. - F.Thompson

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.