2013-10-13 106 views
1

我对Java相当新,并且在理解我需要做什么时遇到了一些麻烦。构造函数和字符串

方向如下:提供一个编写简单字母的类。在构造函数中,提供发件人和收件人的名称:

public Letter (String from, String to) 

提供一种方法。

我有几件事情,如果有人可以澄清将是一个巨大的帮助。 我只是对构造函数有点困惑。如果我没有错误的构造是:

public Letter (String from, String to) 

我需要做些什么。将名称从或改为名称。我试图将它们设置为变量,但我认为这是错误的 东西这样from="Dylan";

此外,我会在这里提供什么方法​​?我只是开始了这一切,发现它很混乱,只需要一些澄清。

+0

如果您希望获得有关您的“Letter”版本的反馈,则应该发布一个新问题。 – tbodt

+0

漂亮的请在上面放糖。 – tbodt

+0

我现在已经删除了你的'Letter'类。别担心,如果您点击说明您的帖子刚编辑过的链接,它仍然存在。 – tbodt

回答

0

你可以像这样开始:

public class Letter { 

    private String source; 
    private String destination; 
    private String content; 

    public Letter (String source, String destination){ 
     this.source = source; 
     this.destination = destination; 
    } 

    public boolean send(){ 
     //do something and return true or false, wether the letter 
     //was successfully sent or not 
     return true; 
    } 

    public void fillContent(String content){ 
     this.content = content; 
    } 

} 

之后,创建将从被发送到B型信的对象

Letter letter = new Letter("A", "B"); 

letter.fillContent("Bienvenido"); 

boolean status = letter.send(); 
+1

嗯,奇怪为什么两个答案都收到-1 – Vallentin

+0

不知道:O/@Vallentin –

+1

我是下来的选民。你不应该把答案发布给这个家伙的作业。只给提示。 – tbodt

-1

你的信类看起来会像下面这样

public class Letter{ 
    private String from, to; 

    public Letter(String from, String to){ 
     this.from = from; 
     this.to = to; 
    } 

    public void someMethod(){//do something} 


} 

你需要声明你的类中的字段将采取inp从你的构造函数。这样你的班级信可以使用你方法中的from和to域

+2

你不应该提供OP的作业答案。只要给他提示。 – tbodt

+0

我的答案与你的答案几乎没有区别。 – newtonrd

+1

那么,你在那里会有一个非常好的'Letter'类,OP可以使用,而不需要真正学习构造函数。 – tbodt

2

构造函数用于将数据传递给对象的初始化过程。在这种情况下,数据是String,from,另一个是String,to。构造函数实际上是一种特殊的方法,它们实际上是名为<init>的方法。因此,您可以像使用任何方法参数一样使用fromto

大多数情况下,如果您想对参数进行任何有用的操作,您可以将它们存储在变量中。这里有一个例子:

public class Car { // this is not the Letter class on purpose, you should write your own 
    private String name; 
    private int year; 

    public Car(String n, int y) { 
     name = n; 
     year = y; 
    } 

    // lots of other methods, which can do anything with name and year 
} 

你可以修改这个为你的Letter类。

相关问题