繁体   English   中英

第一次使用构造函数

[英]First time using constructors

它编译得很好……但是当我尝试输入索引(作为整数)时会抛出“ java.lang.NullPointerException ”错误。 我以为我已经给了 index 一个 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);
    }
}

myLine似乎没有任何内容。

替换Insert insert = new Insert(str, index); with Insert insert = new Insert(str, index,myLine); .

public Insert (String s, int i)public Insert (String s, int I, String myLine)

this.myLine = myLine; 在构造函数中

你的构造函数应该是

public Insert(String s, int i, String r) {
    str = s;
    num = i;
    myLine = r;
}

并传递这样的值“Insert insert = new Insert(str, index,myLine);”

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM