Java 将字符串从一个类传递到另一个类
如何将字符串变量或字符串对象从一个类传递到另一个类? 我有两天的时间来解决这个问题Java 将字符串从一个类传递到另一个类,java,Java,如何将字符串变量或字符串对象从一个类传递到另一个类? 我有两天的时间来解决这个问题 一个类从键盘获取数据,第二个类应该在控制台中打印数据。在接受扫描仪输入的类内部 variableName ClassName = new Classname(); variablename.methodToPrintString(string); 教科书在这种情况下总是有帮助的。从以下代码中获取一些帮助:- public class ReadFrom { private String stringToSh
一个类从键盘获取数据,第二个类应该在控制台中打印数据。在接受
扫描仪
输入的类内部
variableName ClassName = new Classname();
variablename.methodToPrintString(string);
教科书在这种情况下总是有帮助的。从以下代码中获取一些帮助:-
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
}
}
有两种方法:
public class MyPrinter
{
public void printString( String string )
{
System.out.println( string );
}
}
MyPrinter myPrinter = new MyPrinter();
myPrinter.printString( input );
public class MyPrinter
{
public static void printStringWithStaticMethod(String string)
{
System.out.println(string);
}
}
MyPrinter.printStringWithStaticMethod( input );
或2。在printer类中创建静态方法,并在main中调用该方法:
MyPrinter myPrinter = new MyPrinter();
myPrinter.printString( input );
public class MyPrinter
{
public static void printStringWithStaticMethod(String string)
{
System.out.println(string);
}
}
MyPrinter.printStringWithStaticMethod( input );
主要是:
MyPrinter myPrinter = new MyPrinter();
myPrinter.printString( input );
public class MyPrinter
{
public static void printStringWithStaticMethod(String string)
{
System.out.println(string);
}
}
MyPrinter.printStringWithStaticMethod( input );
使用
System.out.println(参数)在第二个类中编写一个方法代码>
将该方法设为静态,然后在第一个方法中调用它,如
ClassName.methodName(parameter)
对你的同学或老师来说,这听起来是个不错的问题。你的类也是一种资源,不要忽视它。那么问题是什么呢?你的代码在哪里?你在两天内写了什么?谢谢你的编辑。。。我试着尽量含糊其辞,因为听起来他正在学习如何做到这一点。