gpt4 book ai didi

Java:从类调用方法/空逻辑错误

转载 作者:行者123 更新时间:2023-12-01 14:49:56 25 4
gpt4 key购买 nike

我很难理解基于对象的编程。我试图从类中调用方法。但是,我调用的只是一个已声明的变量,而我稍后会尝试拉取该变量。 (我确信我的术语有问题 - 请随时纠正)

我遇到逻辑错误。我得到的不是一个值,而是“null”。

类(class):

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++;
} } }

最佳答案

  1. 您永远不会分配给成员变量 oddsUnderpowersTwoUnder。因此,当您读取它们时,它们当然是 null,而当您尝试打印它们时,您有一个 NullPointerException,它会打印“null”。

  2. 您可能实际上想要调用同名的方法而不是获取变量

         System.out.println("Odds under: " + num.oddsUnder());
    System.out.println("Powers of 2 under: " + num.powersTwoUnder());

关于Java:从类调用方法/空逻辑错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14987543/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com