I am having diffculty with trying to assign value to array elements based on a userinput and checking the array element's value in another class. When I do that I get null and I am not sure why and how to fix it.
I have no expereince with java, just started learning it and doing it as part of uni course.
Any help is appreciated and thank you.
Class 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;
}
}
Class 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");
}
}
}
I think you're confusing your method calls a bit. In class 2, you have a line:
String check[] = input.getError();
That should probably be:
String check[] = checkError.getError();
As the getError()
method is in your first class (ErrorHandling) and not the UserInterface
class.
Also, you assign Hello
to errorMessage[0]
and not hey
, so that might be failing in your last few lines in class 2.
If you're just starting out with Java I recommend reading up on Class Structure to understand this (as well as Arrays ).
**EDIT
String comparison in Java doesn't work using the ==
operator. As they are objects and not primitive data types, you must use .equals
.
check[0].equals("Hello")
Invoke checkError.inputCheck()
in the main program otherwise errorMessage
will not get initialized.
Some tweaks in your code that will help to execute:
Class 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;
}
}
Class 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");
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.