提问人:RazaHaider 提问时间:5/16/2022 更新时间:5/16/2022 访问量:62
变量在构造函数中定义,但抛出 NullPointerexception [duplicate]
Variable is defined in constructor but throwing NullPointerexception [duplicate]
问:
我是 Java 的新手,我正在练习字符串,但是当我运行它时,它会抛出 NullPointeException
我定义了一个构造函数,其值为String s1,stopCodon,startCodon。
它接受 s1 的值,但不接受 stopCodon,startCodon,
当我将值放入实例变量中时,它可以正常工作
请解释一下,以便它对我有所帮助......
/* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Codechef
{
String s1;
String startCodon;
String stopCodon;
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
//String s1;
//String startCodon;
//String stopCodon;
Codechef test1 = new Codechef();
test1.testSimpleGene();
}
public void testSimpleGene(){
System.out.println("Gene Strand is = " + s1);
System.out.println("Gene1 is = " + findSimpleGene(s1));
System.out.println("Gene2 is = " + findSimpleGene(s1,startCodon,stopCodon));
}
private String findSimpleGene(String dna,String x,String y){
String dnaResult = "";
int startIndex = dna.toUpperCase().indexOf(x);
if (startIndex == -1){
return "";
}
int stopIndex = dna.toUpperCase().indexOf(y,startIndex+3);
if (stopIndex == -1){
return "";
}
//System.out.println(startIndex +" Part2 "+ (stopIndex));
if((stopIndex - startIndex)%3 == 0){
dnaResult = dna.substring(startIndex,stopIndex+3);
}
return dnaResult;
}
public String findSimpleGene(String dna){
String dnaResult = "";
int startIndex = dna.indexOf(startCodon);
if (startIndex == -1){
return "";
}
int stopIndex = dna.indexOf(stopCodon,startIndex+3);
if (stopIndex == -1){
return "";
}
//System.out.println(startIndex +" "+ (stopIndex));
if((stopIndex - startIndex)%3 == 0){
dnaResult = dna.substring(startIndex,stopIndex+3);
}
return dnaResult;
}
Codechef(){
String s1 = "taaatg";
String startCodon = "TAA";
String stopCodon = "ATG";
}
}
错误
at Codechef.findSimpleGene(Main.java:45)
at Codechef.testSimpleGene(Main.java:24)
at Codechef.main(Main.java:20)```
答:
0赞
Dawood ibn Kareem
5/16/2022
#1
将构造函数更改为如下所示。
public Codechef(){
s1 = "taaatg";
startCodon = "TAA";
stopCodon = "ATG";
}
通过在每行的开头添加单词,您实际上是在构造函数中声明局部变量。您不希望这样做,因为您希望使用对象中的字段,而不是使用其他变量。String
0赞
happy songs
5/16/2022
#2
如注释中所述,您正在构造函数中定义新的局部变量,这些变量恰好与类字段变量同名。
在构造函数中,您应该分配类字段 (, , ) 的值:s1
startCodon
stopCodon
Codechef(){
s1 = "taaatg";
startCodon = "TAA";
stopCodon = "ATG";
}
但是,如果存在与字段变量(对象的属性)同名的局部变量,则可以使用关键字 this
引用字段变量:
Codechef(){
String s1 = "local variable";
this.s1 = "taaatg";
startCodon = "TAA";
stopCodon = "ATG";
}
评论