[英]First time using constructors
It compiles just fine... but throws a " java.lang.NullPointerException
" error on when I try to enter the index (as an integer).它编译得很好……但是当我尝试输入索引(作为整数)时会抛出“ java.lang.NullPointerException
”错误。 I thought I already gave index an int type so I'm not sure why this happens.我以为我已经给了 index 一个 int 类型,所以我不确定为什么会发生这种情况。
I'm new to java so if you guys have any pointers on something else I need to look into or try those tips, would be appreciated as well.我是 Java 新手,所以如果你们有任何关于我需要研究或尝试这些技巧的其他建议,也将不胜感激。
import java.util.Scanner;
class LineEditor
{
public static void main (String [ ] args)
{
//variables
String myLine;
String str;
int index;
Scanner scan = new Scanner(System.in);
//creates original myLine
myLine = new String ("Computer Science");
System.out.println ("The original string of text is: " + myLine);
//variable inputs
System.out.println("Enter a string to alter myLine: ");
str = scan.next();
System.out.println("Enter an index for the string to be inserted at: ");
index = scan.nextInt();
Insert insert = new Insert(str, index);
System.out.println ("The altered string is: " + insert.strIntoMyLine());
}
}
class Insert
{
String str;
int index;
String myLine;
public Insert (String s, int i)
{
str = s;
index = i;
}
String strIntoMyLine()
{
String part1;
String part2;
part1 = myLine.substring (0, index);
part2 = myLine.substring (index);
return (part1 + str + part2);
}
}
It seems that there is nothing present in myLine
. myLine
似乎没有任何内容。
Replace Insert insert = new Insert(str, index);
替换Insert insert = new Insert(str, index);
with Insert insert = new Insert(str, index,myLine);
with Insert insert = new Insert(str, index,myLine);
. .
and public Insert (String s, int i)
with public Insert (String s, int I, String myLine)
和public Insert (String s, int i)
和public Insert (String s, int I, String myLine)
Also还
this.myLine = myLine;
in the constructor在构造函数中
your constructor should be你的构造函数应该是
public Insert(String s, int i, String r) {
str = s;
num = i;
myLine = r;
}
and pass value like this "Insert insert = new Insert(str, index,myLine);"并传递这样的值“Insert insert = new Insert(str, index,myLine);”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.