英文:
Make a String in java Global
问题
我是一名安卓开发者,我已经创建了一个用于生成随机6位数字OTP的字符串,该字符串位于`protected void onCreate(Bundle savedInstanceState){}`中,是Java程序中的第一件事。
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字符串,但我不知道如何做。
任何形式的帮助都将不胜感激。
英文:
I am an Android developer and I have made a string for generating a random 6-digit OTP which is there in the protected void onCreate(Bundle savedInstanceState) {
, the first thing in a java program.:
String otp = new DecimalFormat("000000").format(new Random().nextInt(999999));
Toast.makeText(getApplicationContext(), "Your OTP is " + otp, Toast.LENGTH_SHORT).show();
I have another public void
in my java program in which I have to call the OTP String but, I don't know how to do that.
Any type of help will be appreciated.
答案1
得分: 0
你可以将字符串定义为类数据成员,然后在onCreate方法中进行初始化,这样同一类中的所有成员都可以访问该数据成员。例如:
String mOTP;
@Override
protected void onCreate(Bundle savedInstanceState) {
mOTP = new DecimalFormat("000000").format(new Random().nextInt(999999));
... 其余代码
}
或者,你可以创建另一个类,命名为Consts或类似的名称,在那里创建一个静态字符串,并且可以从项目中的任何地方访问它。
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));
... 其余代码
}
英文:
You can either define the string as a class data member, initialize it in the onCreate method and have everyone in the same class access that data member.
As in:
String mOTP;
@Override
protected void onCreate(Bundle savedInstanceState) {
mOTP = new DecimalFormat("000000").format(new Random().nextInt(999999));
... Rest of code
}
Or, you can create another class, named Consts or something of the sort, and create a static String there and access it from where ever in your project.
public static class Consts{
public static String OTP_STRING;
}
and then in mainActivity
@Override
protected void onCreate(Bundle savedInstanceState) {
Consts.OTP_STRING = new DecimalFormat("000000").format(new Random().nextInt(999999));
... Rest of code
}
答案2
得分: 0
定义你的字符串变量,可以将其定义为类(静态)变量或类的实例变量。
示例解决方案
public class Main{
String otp; //在这里定义你的变量
public void method1(){
//现在你可以访问变量 otp 并进行更改
}
public void method2(){
//现在你可以访问变量 otp 并进行更改
}
}
英文:
Define your String variable either as a class(static) variable or instance variable in your class.
Sample solution
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
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论