使用实例参数编写Java类,检索参数并打印结果

时间:2012-03-29 11:44:27

标签: java

基本上,我需要创建一个新的简单Java类,它从我的表单中检索值(我将其设计为我的流程并部署为Web应用程序),一旦调用Java类中的方法然后调用Java类应该只是打印出从控制台或文本文件中的表单中获取的值(例如system.println.out ...)。

使用一些实例参数创建一个类。打印一行,说明这些参数的初始值。

我是Java的新手,几天前才开始使用,但将此要求作为项目的一部分。

请有人帮助编写此Java类。

2 个答案:

答案 0 :(得分:1)

我建议你阅读一些java初学者书籍(或javadoc),以便在尝试写错之前理解java中的Class构造函数概念。

粗略的课程可能是这样的:

public class myClass{
   int param1;
   int param2;

   public myClass(int firstparam, int secondparam){
     this.param1 = firstparam;
     this.param2 = secondparam;
   }
}

public static void main(){ 
    myClass c = new myClass(1,2);
    System.out.println(c.param1 + c.param2);
}

如果你不明白这一点,请学习java基础..

答案 1 :(得分:1)

您可以简单地创建一个类及其构造函数,如:

public class Test {

    //a string representation that we will initialize soon
    private String text;

    //Firstly you have to instantiate your Test object and initialize your "text"
    public Test(String text) {
        this.text = text;
        //System.out.println(text);
        //You can print out this text directly using this constructor which also             
        //has System.out.println()
    }

    //You can just use this simple method to print out your text instead of using the 
    //constructor with "System.out.println"
    public void printText() {
        System.out.println(this.text);//"this" points what our Test class has
    }

}

使用这个类就像:

  public class TestApp {
      public static void main(String[] args) {

          Test testObject = new Test("My Text");

          /*if you used the constructor with System.out.println, it directly prints out  
          "My Text"*/

          /*if your constructor doesn't have System.out.println, you can use our      
          printText() method //like:*/
          testObject.printText();
      }
  }