它编译得很好......但是会抛出一个" java.lang.NullPointerException
"我尝试输入索引时出错(作为整数)。我以为我已经给了一个int类索引,所以我不确定为什么会这样。
我是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);
}
}
答案 0 :(得分:0)
似乎myLine
中没有任何内容。
将Insert insert = new Insert(str, index);
替换为Insert insert = new Insert(str, index,myLine);
。
和public Insert (String s, int i)
与public Insert (String s, int I, String myLine)
另外
构造函数中的 this.myLine = myLine;
答案 1 :(得分:0)
你的构造函数应该是
public Insert(String s, int i, String r) {
str = s;
num = i;
myLine = r;
}
并像这样传递值“Insert insert = new Insert(str,index,myLine);”