【发布时间】:2015-10-10 23:25:55
【问题描述】:
如何将字符串变量或字符串对象从一个类传递到另一个类? 我有 2 天的时间来解决这个问题。
一个类从键盘获取数据,第二个类应该在控制台中打印。
【问题讨论】:
-
对于您的同学或教师来说,这听起来是个好问题。你的班级也是一种资源,不要忽视它。
-
那是什么问题?您在 2 天内编写的所有代码在哪里?
标签: java
如何将字符串变量或字符串对象从一个类传递到另一个类? 我有 2 天的时间来解决这个问题。
一个类从键盘获取数据,第二个类应该在控制台中打印。
【问题讨论】:
标签: java
从下面的代码中获取一些帮助:-
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
}
}
【讨论】:
用System.out.println(parameter); 在你的第二个类中编写一个方法
将方法设为静态,然后在第一个方法中调用它,例如
ClassName.methodName(parameter)
【讨论】:
有两种方式:
创建打印机类的实例并调用打印机对象上的方法:
public class MyPrinter
{
public void printString( String string )
{
System.out.println( string );
}
}
在你的主要:
MyPrinter myPrinter = new MyPrinter();
myPrinter.printString( input );
或者 2. 你在你的打印机类中创建一个静态方法并在你的 main 中调用它:
public class MyPrinter
{
public static void printStringWithStaticMethod(String string)
{
System.out.println(string);
}
}
在你的主要:
MyPrinter.printStringWithStaticMethod( input );
【讨论】:
接受Scanner 输入的内部类
variableName ClassName = new Classname();
variablename.methodToPrintString(string);
教科书总能在这种情况下提供帮助。
【讨论】: