![](/img/trans.png)
[英]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.