在Java Global中创建字符串

问题描述

我是一名Android开发人员,我编写了一个用于生成随机6位OTP的字符串,该字符串位于Java软件中的第一项protected void onCreate(Bundle savedInstanceState) {中。:

String otp = new DecimalFormat("000000").format(new Random().nextInt(999999));
Toast.makeText(getApplicationContext(),"Your OTP is " + otp,Toast.LENGTH_SHORT).show();

我的Java程序中还有一个public void,我必须在其中调用OTP字符串,但是我不知道该怎么做。

任何类型的帮助将不胜感激。

解决方法

在类中将String变量定义为类(静态)变量或实例变量。

示例解决方案

public class Main{
   String otp; //Define your variable here


   public void method1(){

      //Now you can access the variable otp and you can make changes

   }

  public void method2(){

     //Now you can access the variable otp and you can make changes


  }

}
,

您可以将字符串定义为类数据成员,在onCreate方法中对其进行初始化,并让同一类中的每个人都可以访问该数据成员。 如:

String mOTP;

@Override
protected void onCreate(Bundle savedInstanceState) {
mOTP = new DecimalFormat("000000").format(new Random().nextInt(999999));
... Rest of code
}

或者,您可以创建另一个名为Consts或此类的类,并在那里创建静态String并从项目中的任何位置访问它。

public static class Consts{
     public static String OTP_STRING;
}

然后进入mainActivity

@Override
protected void onCreate(Bundle savedInstanceState) {
Consts.OTP_STRING = new DecimalFormat("000000").format(new Random().nextInt(999999));
... Rest of code
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...