简体   繁体   中英

Toast with custom message

I start to learn Android programming, and now I try to display a toast with a custom string.

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();

Any ideas what I'm doing wrong? I'm getting the following error message:

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)

Ok. Looks like int cannot be converted to String .

So this fixed my problem:

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();

Even though you've found the answer yourself, I still want to provide some examples to make sure that you understand how String#format(String, Object...) works:

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);

More explanation about java formatting can be reached at:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM