[英]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.我有 2 天的时间来解决这个问题。
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:有两种方式:
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:或 2. 在打印机类中创建静态方法并在主类中调用它:
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);
使用System.out.println(parameter);
在你的第二个类中编写一个方法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接受Scanner
输入的内部类
variableName ClassName = new Classname();
variablename.methodToPrintString(string);
A textbook can always help in this situation.在这种情况下,教科书总能提供帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.