Java Test类

时间:2014-09-08 18:36:14

标签: java generics

我对编程还很陌生,需要对我正在编写的程序提供一点帮助。它由两个类组成,一个是通用的OrderedPair类和一个ObjectPairTest类。到目前为止,这是我的OrderedPair类:  我使用了以下评论中的一些建议,并将我的ObjectPair类更改为:

    package lab2;

    public class OrderedPair<F, S>{ 


public F getFirst;
public S getSecond;

private F first;
private S second;

public OrderedPair(F first, S second ){
    this.first = first;
    this.second = second;
    }
    public F getFirst() { return first; }
    public S getSecond() {return second;}
    public String toString() {return first.toString() + " | "+second.toString();}
public static final OrderedPair<String, Integer> c1 = new OrderedPair<String, Integer>("Pi", 3);
public static final OrderedPair<String,String> c2 = new OrderedPair<String, String>("Great", "Super");
public static final OrderedPair<Integer, Integer> c3 = new OrderedPair<Integer, Integer>(1, 2);
public static final OrderedPair<Float, String> c4 = new OrderedPair<Float, String>( 5f, "Maximum");
public static final OrderedPair<Integer, Float> c5 = new OrderedPair<Integer, Float>(69, 69f);

    }

我的ObjectPairTest类如下:

package lab2;

    public class OrderedPairTest{

public static void main(String[] args){
    System.out.println(c1.toString());
    System.out.println(c2.toString());
    System.out.println(c3.toString());
    System.out.println(c4.toString());
    System.out.println(c5.toString());
}//End class Main
}//End class OrderedPairTest

但是,当我尝试运行时,它会给出错误消息:

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
c1 cannot be resolved
c2 cannot be resolved
c3 cannot be resolved
c4 cannot be resolved
c5 cannot be resolved
at lab2.OrderedPairTest.main(OrderedPairTest.java:6)

到目前为止,谢谢大家的帮助。

2 个答案:

答案 0 :(得分:0)

public class OrderedPair<F, S>{ 

    private F first;
    private S second;

    public OrderedPair(F first, S second ){
        this.first = first;
        this.second = second;
    }

    public F getFirst() { return first; }
    public S getSecond() {return second;}
    public String toString() {return first.toString() + " | "+second.toString();}

    public static void test(){
        //Five pairs of data 
        OrderedPair<String, Integer> c1 = new OrderedPair<String, Integer>("Pi", 3);
        OrderedPair<String,String> c2 = new OrderedPair<String, String>("Great", "Super");
        OrderedPair<Integer, Integer> c3 = new OrderedPair<Integer, Integer>(1, 2);
        OrderedPair<Float, String> c4 = new OrderedPair<Float, String>( 5f, "Maximum");
        OrderedPair<Integer, Float> c5 = new OrderedPair<Integer, Float>(69, 69f);
        System.out.println(c1.toString());
    }
}

答案 1 :(得分:-1)

添加“OrderedPair”。在所有这些变量面前 public static void main(String[] args){ System.out.println(OrderedPair.c1.toString()); System.out.println(OrderedPair.c2.toString()); System.out.println(OrderedPair.c3.toString()); System.out.println(OrderedPair.c4.toString()); System.out.println(OrderedPair.c5.toString()); }