首页 > 解决方案 > Java - 在类定义中找不到错误

问题描述

我对以下代码有疑问。这是一项考试任务,我无法弄清楚给定代码中的错误是什么。我们应该在 A 类中找到错误,该错误会阻止我们使用 JUnit 测试代码。

import java.util.List;
import java.util.ArrayList;

public class A {

private List<String> s;

    public A() {
        s = new ArrayList<String>();
        s.add("Bob");
        s.add("Alice");
        s.add("Eve");
    }

    public String s(B b){
        int t = b.t();
        String r = "Hello ";
        for (String z : s) {
            boolean x = b.f(t, 5);
            if (x) {
                r = r + z;
            }
        }
        return r;
    }

    // main added by myself for testing purpose
    public static void main(String[] args){
        A test = new A();
        test.s();
    }
}

interface B{
int t();//complex calculus

boolean f(int a, int b); // complex algorithm
}

我认为,该错误与以下内容有关:

  1. s(B b)与属性同名的方法s
  2. interface B未实施

非常感谢您的帮助!

标签: javalogic

解决方案


您可以查看此代码以供参考:

import java.util.List;
import java.util.ArrayList;

public class A implements B{

private List<String> s;

public A() {
    s = new ArrayList<String>();
    s.add("Bob");
    s.add("Alice");
    s.add("Eve");
}
//overridden method from interface B
public int t(){
  //what you want this method to do
}
//overridden method from interface B
public boolean f(int a, int b){
  //what you want this method to do
}
public String s(){ 
    A test = new A();
    int t = test.t(); 
    String r = "Hello ";
    for (String z : s) {
        boolean x = test.f(t, 5);
        if (x) {
            r = r + z;
        }
    }
    return r;
}

// main added by myself for testing purpose
public static void main(String[] args){
    A test = new A();
    System.out.println(test.s()); //printing the result of `test.s()`
}
}
interface B{
  int t();//complex calculus
  boolean f(int a, int b); // complex algorithm
}

您可以参考此链接以进一步了解。

资料来源: https ://www.geeksforgeeks.org/interfaces-in-java/


推荐阅读