【问题标题】:Toast with custom message带有自定义消息的吐司
【发布时间】:2016-09-11 09:14:18
【问题描述】:

我开始学习 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();

任何想法我做错了什么?我收到以下错误消息:

错误:(40, 40) 错误:找不到适合格式(随机)方法的方法 String.format(String,Object...) 不适用(参数不匹配;随机无法转换为字符串)方法字符串。 format(Locale,String,Object...) 不适用(参数不匹配;Random 无法转换为 Locale)

【问题讨论】:

  • 到底出了什么问题?您收到错误消息吗?
  • 是的。错误:(40, 40) 错误:找不到适合格式(随机)方法的方法 String.format(String,Object...) 不适用(参数不匹配;随机无法转换为字符串)方法 String.format(Locale ,String,Object...) 不适用(参数不匹配;Random 无法转换为 Locale)
  • @Joe 我猜你想显示i,所以你必须把它放在String.format()而不是你的Random对象中,比如String message = String.format(i);

标签: java android android-toast


【解决方案1】:

即使您自己找到了答案,我仍然想提供一些示例以确保您了解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格式化的解释可以到:

【讨论】:

    【解决方案2】:

    好的。看起来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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-04-15
      • 1970-01-01
      • 1970-01-01
      • 2021-09-06
      • 1970-01-01
      • 1970-01-01
      • 2015-01-04
      相关资源
      最近更新 更多