It compiles just fine... but throws a " java.lang.NullPointerException
" error on when I try to enter the index (as an integer). I thought I already gave index an int type so I'm not sure why this happens.
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.
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
.
Replace Insert insert = new Insert(str, index);
with Insert insert = new Insert(str, index,myLine);
.
and public Insert (String s, int i)
with 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);"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.