-2

当我尝试调用时,Eclipse 给了我静态引用非静态对象错误isOdd()Number.java但由于isOdd()不包含任何参数,我不能像往常一样调用外部方法。

NumberAnalyzer.java

import java.util.ArrayList;
import java.util.Scanner;

import com.sun.xml.internal.ws.api.pipe.NextAction;

import static java.lang.System.*;

public class NumberAnalyzer
{
private ArrayList<Number> list;

public NumberAnalyzer()
{

}

public NumberAnalyzer(String numbers)
{
    list = new ArrayList<Number>();
    String nums = numbers;
    Scanner chopper = new Scanner(nums);
    while(chopper.hasNext()){
        int num = chopper.nextInt();
        list.add(new Number(num));
    }
    chopper.close();
    System.out.println(list);
}

public void setList(String numbers)
{
    list = new ArrayList<Number>();
    String nums = numbers;
    Scanner chopper = new Scanner(nums);
    while(chopper.hasNext()){
        int num = chopper.nextInt();
        list.add(new Number(num));
    }
    chopper.close();

}

public int countOdds()
{
  int oddCount=0;
  for(int i = 0; i < list.size(); i++){
      if(Number.isOdd()== true){
          oddCount++;
      }
  }
  return oddCount;
}

public int countEvens()
{
  int evenCount=0;



  return evenCount;
}

public int countPerfects()
{
    int perfectCount=0;



  return perfectCount;
}

public String toString( )
{
    return "";
}
}

数字.java

public class Number
{
private Integer number;

public Number()
{


}

public Number(int num)
{
    number = num;
}

public void setNumber(int num)
{
    number = num;
}

public int getNumber()
{
    return number;
}   

public boolean isOdd()
{
    if(number%2==0){
        return false;
    }
    return true;
}

public boolean isPerfect()
{
    int total=0;
    for(int i = 1; i < number; i++){
        if(number%i==0){
            total+= i;
        }
    }


    return (number==total);
}   

public String toString( )
{
    String output = getNumber() + "\n" + getNumber()+ "isOdd == " + isOdd() + "\n" + getNumber()+ "isPerfect==" + isPerfect()+ "\n\n";
    return output;
}
}

跑步者班

import java.util.ArrayList;
import java.util.Scanner;
import static java.lang.System.*;

public class Lab16b
{
public static void main( String args[] )
{
    NumberAnalyzer test = new NumberAnalyzer("5 12 9 6 1 4 8 6");
    out.println(test);
    out.println("odd count = "+test.countOdds());
    out.println("even count = "+test.countEvens());
    out.println("perfect count = "+test.countPerfects()+"\n\n\n");


    //add more test cases


}
}
4

2 回答 2

1

你似乎有list全球性。做就是了

  for(int i = 0; i < list.size(); i++){
          if(list.get(i).isOdd()){
              oddCount++;
          }
      }

这样你实际上得到了一个Numberfromlist并且可以调用该isOdd()方法。

请注意,您不需要== true检查。

于 2013-01-10T02:30:47.603 回答
1

Number.isOdd适用于一个Number实例。由于您的for循环覆盖了List( list) 的索引范围Numbers,因此您可以替换

if (Number.isOdd() == true) {

if (list.get(i).isOdd() == true) {

或更好

if (list.get(i).isOdd()) {
于 2013-01-10T02:31:52.920 回答