[英]Although hash values are different, still why are my objects stored in the same location?
[英]Instance variable with the same value for different objects although different values were assigned
首先,在發布我的問題之前,讓我請大家停止對我的問題進行投票,即使他們對你似乎很愚蠢,該站點對我來說是重要的場所,它對我的java疑問有很多幫助,這對我有很大幫助。禁令對我來說將是一個沉重的挫折,因此即使不回答也將有所幫助! 現在問題
我有這種方法是我通過用戶輸入將值分配給setter方法
public void addName() {
Scanner input = new Scanner(System.in);
System.out.println("Do you want to add a citizen name?");
String answer = input.nextLine();
while (!answer.equals("y") || (!answer.equals("n"))) {
if (answer.equals("y")) {
String giveName = input.nextLine();
this.setName(giveName);
break;
} else if (answer.equals("n")) {
System.out.println("Not adding a name!");
break;
}else{System.out.println("Please choose y or n!");
answer = input.nextLine();}
}
}
稍后從對象p1
和對象p2
在主方法中調用此方法,並為每個實例變量名稱分配一個不同的值
import java.util.ArrayList;
import java.util.Scanner;
public class MainClass {
public static void main(String[] args) {
ArrayList<Pessoas> lista = new ArrayList<Pessoas>();
Pessoas p1 = new Portugueses();
Pessoas p2 = new Alemaes();
p1.addName();
p2.addName();
System.out.println(p1.getName());
System.out.println(p2.getName());
}
}
但是當我在main的末尾調用getName()
方法時, p1
和p2
都具有相同的值! 每個對象都不應獲取自己的實例變量副本嗎?
問題出在您的addName()
函數中。 運行循環( while (!answer.equals("y") || (!answer.equals("n")))
),直到輸入y
或n
。 因此,一旦您輸入它,循環就會停止。
在循環中,檢查輸入的內容是否包含y
或n
。 現在問題應該很清楚了。 您的循環不會在輸入這兩個值的情況下運行,但是您要在循環內部檢查是否輸入了其中兩個值。
兩個小小的個人提示(每個人都有另一種風格):不要使用break;
讓循環結束自己。 使用布爾變量執行此操作並更新其狀態。
第二個提示是使用一個Scanner
-Object。 例如,您可以將Scanner
參數添加到addName
函數中。 只需在MainClass
初始化一個。
這些應用於您的代碼的提示和修復可能看起來像這樣:
public void addName(Scanner input) {
System.out.println("Do you want to add a citizen name?");
String answer;
boolean isAnotherInputNeeded = true;
while (isAnotherInputNeeded) {
answer = input.nextLine();
if (answer.equals("y"))
{
System.out.println("What's the name?");
String giveName = input.nextLine();
this.setName(giveName);
isAnotherInputNeeded= false;
}
else if (answer.equals("n"))
{
System.out.println("Not adding a name!");
this.setName("No name entered");
isAnotherInputNeeded= false;;
}
else
{
System.out.println("Please choose y or n!");
}
input.reset();
}
}
和你的MainClass
:
import java.util.ArrayList;
import java.util.Scanner;
public class MainClass {
public static void main(String[] args) {
ArrayList<Pessoas> lista = new ArrayList<Pessoas>();
Pessoas p1 = new Pessoas();
Pessoas p2 = new Pessoas();
Scanner input = new Scanner(System.in);
p1.addName(input);
p2.addName(input);
System.out.println("You entered the following names:");
System.out.println(p1.getName());
System.out.println(p2.getName());
}
}
希望有幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.