簡體   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