简体   繁体   中英

Passing String from one class to another

How can I pass string variable or String object from one class to another? I've 2 days on this problem.

One class get data from keyboard and second one should print it in console.

Take some help from the below code:-

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
  }
}

There are two ways:

  1. create an instance of your printer class and evoke the method on the printer object:

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

in your main:

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

or 2. you create a static method in your printer class and evoke it in your main:

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

in your main:

MyPrinter.printStringWithStaticMethod( input );

Write a method inside your second class with System.out.println(parameter); Make the method static and then invoke this in first method like

ClassName.methodName(parameter)

Inside class that accepts Scanner input

variableName ClassName = new Classname();

variablename.methodToPrintString(string);

A textbook can always help in this situation.

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.

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