簡體   English   中英

將字符串從一個類傳遞到另一個類

[英]Passing String from one class to another

如何將字符串變量或字符串對象從一個類傳遞到另一個類? 我有 2 天的時間來解決這個問題。

一類從鍵盤獲取數據,第二類應該在控制台中打印出來。

從以下代碼中獲取一些幫助:-

public class ReadFrom {
  private String stringToShow; // String in this class, which other class will read
  public void setStringToShow(String stringToShow) {
    this.stringToShow = stringToShow;
  }

  public String getStringToShow() {
    return this.stringToShow;
  }
}

class ReadIn {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in); // for taking Keyboard input
    ReadFrom rf = new ReadFrom();
    rf.setStringToShow(sc.nextLine()); // Setting in ReadFrom string
    System.out.println(rf.getStringToShow()); // Reading in this class
  }
}

有兩種方式:

  1. 創建打印機類的實例並調用打印機對象上的方法:

     public class MyPrinter { public void printString( String string ) { System.out.println( string ); } }

在你的主要:

MyPrinter myPrinter = new MyPrinter();
myPrinter.printString( input );

或 2. 在打印機類中創建靜態方法並在主類中調用它:

public class MyPrinter
{
    public static void printStringWithStaticMethod(String string)
    {
        System.out.println(string);
    }
}

在你的主要:

MyPrinter.printStringWithStaticMethod( input );

使用System.out.println(parameter);在你的第二個類中編寫一個方法System.out.println(parameter); 使方法靜態,然后在第一個方法中調用它,例如

ClassName.methodName(parameter)

接受Scanner輸入的內部類

variableName ClassName = new Classname();

variablename.methodToPrintString(string);

在這種情況下,教科書總能提供幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM