FORGOT.JAVA在这里,我创建了一个随机数并将其转换为字符串
Random rand=new Random();
int id=rand.nextInt(10000);
System.out.printf("%04d%n",id);
final String ki=Integer.toString(id);
System.out.printf(ki);
OTP.JAVA在这里,我使用该随机数将其与用户输入进行比较。.但是来自forgot.java的值为null,为什么它为null ???
forgot ff=new forgot();
String s=ff.ki;
System.out.print(s);
if (o.compareTo(s) > 0)
System.out.println("Strings are'nt same");
else if (o.compareTo(s) < 0)
System.out.println("The first string is smaller than the second.");
else
System.out.println("Both the strings are equal.");
//int ch=ff.ki;
}
}
答案 0 :(得分:0)
似乎是范围问题。您从FORGOT.JAVA发布的代码片段不足以准确地找出问题所在。但是您在片段中定义了变量ki
。因此,它将不在代码片段所在的方法/构造函数之外提供。
查看来自OPT.JAVA的第二个片段,您将创建一个新的FORGOT,然后引用一个名为ki的字段。因此,为了进行编译,您可能对FORGOT类具有以下内容。
public class FORGOT {
public String ki;
public FORGOT() {
Random rand=new Random();
int id=rand.nextInt(10000);
System.out.printf("%04d%n",id);
final String ki=Integer.toString(id);
System.out.printf(ki);
}
}
尽管看起来像是将ki设置为随机数,但实际上是在构造函数的范围内创建了一个名为ki的新变量,并将其设置为随机数。构造函数返回后,该变量就消失了,您将无法再引用它。
要设置公共变量ki,只需从设置ki的位置删除final String
位即可。
即
public class FORGOT {
public String ki;
public FORGOT() {
Random rand=new Random();
int id=rand.nextInt(10000);
System.out.printf("%04d%n",id);
ki=Integer.toString(id);
System.out.printf(ki);
}
}