[英]How to assign array elements to private variable and use them in another class?
[英]Trying to assign value to array elements and return it in another class to work with but not working
我很难尝试根据用户输入将值分配给数组元素并在另一个类中检查数组元素的值。 当我这样做时,我会得到null,并且不确定为什么以及如何解决它。
我对Java没有任何经验,只是开始学习它并将其作为uni课程的一部分进行。
任何帮助表示赞赏,谢谢。
1类
public class ErrorHandling {
String[] errorMessage = new String[4];
public void inputCheck() {
UserInterface input = new UserInterface();
int[] checkUserInput = input.getInput();
if (checkUserInput[0] < 20 || checkUserInput[0] > 80) {
errorMessage[0] = "Hello";
}
if (!(checkUserInput[1] <= 10 && checkUserInput[1] % 2 == 0)) {
errorMessage[2] = "Hey";
}
}
public String[] getError() {
return errorMessage;
}
}
2级
public class MainProgram {
public static void main(String[] args) {
UserInterface input = new UserInterface();
input.askZigZag();
ErrorHandling checkError = new ErrorHandling();
String check[] = checkError.getError();
if (check[0] == ("Hello")) {
System.out.println("yh");
}
}
}
我认为您有点混淆您的方法调用。 在第2课中,您有一行:
String check[] = input.getError();
那应该是:
String check[] = checkError.getError();
由于getError()
方法在您的第一个类(ErrorHandling)中,而不在UserInterface
类中。
另外,您将Hello
分配给errorMessage[0]
而不是hey
,因此在类2的最后几行中可能会失败。
如果您只是刚开始使用Java,那么我建议您阅读类结构以了解这一点(以及Arrays )。
**编辑
使用==
运算符无法在Java中进行字符串比较。 由于它们是对象而不是原始数据类型,因此必须使用.equals
。
check[0].equals("Hello")
在主程序中调用checkError.inputCheck()
,否则errorMessage
将不会初始化。
您的代码中的一些调整将有助于执行:
1类
public class ErrorHandling {
String[] errorMessage = new String[4];
public void inputCheck() {
UserInterface input = new UserInterface();
int[] checkUserInput = input.getInput();
// If you want to use askZigZag... use it somewhere inside this function
// since you have already declared the object of UserInterface.
if (checkUserInput[0] < 20 || checkUserInput[0] > 80) {
errorMessage[0] = "Hello";
}
if (!(checkUserInput[1] <= 10 && checkUserInput[1] % 2 == 0)) {
errorMessage[2] = "Hey";
}
}
public String[] getError() {
return errorMessage;
}
}
2级
public class MainProgram {
public static void main(String[] args) {
// UserInterface input = new UserInterface();
// input.askZigZag();
ErrorHandling checkError = new ErrorHandling();
checkError.inputCheck();
String check[] = checkError.getError();
if (check[0].equals("Hello")) {
System.out.println("yh");
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.