2016-09-10 2 views
0

Je commence à apprendre la programmation Android, et maintenant j'essaie d'afficher un toast avec une chaîne personnalisée.Toast avec message personnalisé

Random r = new Random(); 
int i = r.nextInt(100 - 90 + 1) + 90; 
String message = String.format(r); 

Toast.makeText(getApplicationContext(), "@".replace(message), Toast.LENGTH_LONG).show(); 

Toutes les idées que je fais mal? J'obtiens le message d'erreur suivant:

Error:(40, 40) error: no suitable method found for format(Random) method String.format(String,Object...) is not applicable (argument mismatch; Random cannot be converted to String) method String.format(Locale,String,Object...) is not applicable (argument mismatch; Random cannot be converted to Locale)

+0

Quel est exactement le problème? Avez-vous un message d'erreur? –

+0

Oui. Erreur: (40, 40) erreur: aucune méthode appropriée trouvée pour le format (aléatoire) méthode String.format (String, Object ...) n'est pas applicable (discordance d'argument; Random ne peut pas être converti en chaîne) méthode Chaîne. format (Locale, Chaîne, Objet ...) n'est pas applicable (discordance d'argument; Random ne peut pas être converti en Locale) – Joe

+0

@Joe Je suppose que vous vouliez afficher 'i', donc vous devez le mettre dans' String.format() 'plutôt que votre objet' Random', comme 'String message = String.format (i);' – Jezor

Répondre

0

Même si vous avez trouvé la réponse vous-même, je veux encore donner quelques exemples pour vous assurer que vous comprenez comment fonctionne String#format(String, Object...):

Random r = new Random(); 
String message = null; 

int i = r.nextInt(100 - 90 + 1) + 90; 
message = String.format("%d", i); 

float f = 0.1; 
message = String.format("%f", f); 

String s = "Hello world"; 
message = String.format("%s", s); 

// "Hello world, f=0.1" 
message = String.format("%s, f=%f", s, f); 

Plus d'explications sur le formatage java peut être contacté à:

0

Ok. On dirait que int ne peut être converti en String.

Alors que ce soit réglé mon problème:

Random r = new Random(); 
int i = r.nextInt(100 - 90 + 1) + 90; 
String message = String.format(Integer.toString(i)); 

Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();