0

オブジェクトベースのプログラミングに頭を悩ませています。クラスからメソッドを呼び出そうとしています。ただし、後で変数をプルしようとしている間、呼び出すのは宣言された変数だけです。(私の用語が間違っていると確信しています - 自由に修正してください)

論理エラーが発生しています。値の代わりに、「null」を取得しています。

クラス:

public class NumberOperations {
   int number;
   String oddsUnder;
   String powersTwoUnder;
   int isGreater;
   String toString;



public NumberOperations(int numberIn) {
   number = numberIn;

}

public int getValue() {
   return number;
}

public String oddsUnder() {
   String output = "";
   int i = 0;
   while (i < number) {
      if (i % 2 != 0) {
         output += i + "\t";
      }
      i++;   
   }
   return output;
}

public String powersTwoUnder() {
   String output2 = "";
   int powers = 1;
   while (powers < number) {
   output2 += powers + "\t";
   powers = powers * 2;
   }
   return output2;
}

public int isGreater(int compareNumber) {
   if (number > compareNumber) {
      return 1;
   }
   else if (number < compareNumber) {
      return -1;
   }
   else {      
      return 0;
   }   
}

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

}          

プログラム:

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

/**  * Demonstrates the NumberOperations class.  */ public class NumberOpsDriver {

   /**
    * Reads a set of positive numbers from the user until the user enters 0.     * Prints odds under and powers of 2 under for each number.      *
    * @param args - Standard commandline arguments
    */    public static void main(String[] args) {

      Scanner in = new Scanner(System.in);

      // declare and instantiate ArrayList with generic type <NumberOperations>
      ArrayList<NumberOperations> numOpsList = new ArrayList<NumberOperations>();

      // prompt user for set of numbers
      System.out.println("Enter a list of positive integers separated "
                        + "with a space followed by 0:");

      // get first user input using in.nextInt()
      int firstInput = in.nextInt();
      // add a while loop as described below:
      while (firstInput != 0) {

         numOpsList.add(new NumberOperations(firstInput));

         firstInput = in.nextInt();
      }     

    // while the input is not "0"
         // add NumberOperations object to array based on user input
         // get the next user input using in.nextInt()

      int index = 0;
      while (index < numOpsList.size()) {
         NumberOperations num = numOpsList.get(index);
         System.out.println("For: " + num);
         System.out.println("Odds under: " + num.oddsUnder);
         System.out.println("Powers of 2 under: " + num.powersTwoUnder);

        // add print statement for odds under num
        // add print statement for powers of 2 under num

         index++;
      }    } }
4

2 に答える 2