使用自定义消息敬酒
Toast with custom message
我开始学习 Android 编程,现在我尝试用自定义字符串显示 toast。
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();
知道我做错了什么吗?我收到以下错误消息:
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)
好的。看起来 int
无法转换为 String
.
所以这解决了我的问题:
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();
即使您自己找到了答案,我仍想提供一些示例以确保您了解 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);
有关 java 格式的更多说明,请访问:
我开始学习 Android 编程,现在我尝试用自定义字符串显示 toast。
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();
知道我做错了什么吗?我收到以下错误消息:
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)
好的。看起来 int
无法转换为 String
.
所以这解决了我的问题:
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();
即使您自己找到了答案,我仍想提供一些示例以确保您了解 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);
有关 java 格式的更多说明,请访问: