我正在編寫程序,要求用戶鍵入產品的七個名稱。我堅持從while循環中退出方法
我試圖做的是如果有重複,然後重複該方法。
我用while while循環但我卡住了。
如果我在第一次放置a,b,c,d,e,f,g,方法結束並轉到下一個方法。
但是如果我輸入a,a,b,c,d,e,f,程序會重複相同的方法,即使我鍵入a,b,c,d,e,f,g,它也會進入無限循環。
這是我的代碼。
在主....
purchasedList.setShopList();
在purchasedList類
...
public void setShopList() {
Scanner keyboard = new Scanner(System.in);
// print out description.
System.out.println("\n- Only have one entry of any type in the item list.");
System.out.println("- The name of items cannot be longer than 16 characters.");
System.out.println("\nType seven products.");
boolean sameNames = true;
while (sameNames == true) {
for (int i=0; i<7; i++) {
String n = keyboard.nextLine();
name.add(n);
name.set(i,name.get(i).toUpperCase());
}
sameNames = checkName();
}
}
// accessor.
public ArrayList<String> getShopList() {
return name;
}
// check duplicate.
public boolean checkName() {
Set<String> uniqueName = new HashSet<String>();
boolean foundName = false;
for (int i=0; i<7; i++) {
if (!uniqueName.add(name.get(i))) { // check duplicate
foundName = true;
}
}
if (foundName == true) {
System.out.println("※ There is a duplicate. Try it again.");
return true;
} else {
return false;
}
}
我檢查名()方法是好的,因爲在去年它的工作我的項目。
在我的最後一個項目,我把while循環主這樣
public static void main(String[] args) {
PurchasedList purchasedList = new PurchasedList();
.
.
.
boolean sameNames = true;
boolean tooLong = true;
while (sameNames == true || tooLong == true) {
System.out.println("\nType seven products.");
purchasedList.setShopList();
sameNames = purchasedList.checkName();
tooLong = purchasedList.checkLength();
}
但是這一次,因爲我的教授要我做所有的操作都在方法中完成的,所以我嘗試修復。
我試圖在過去8小時內自己解決,但我無法得到解決方案。
請幫幫我。
謝謝。
你是100%肯定你的循環是',而(sameNames ==真){'和'不同時(sameNames =真){'?無論哪種方式,你應該簡單地寫'while(sameNames){'... – jlordo
即使我使用'while(sameNames){',它仍然是相同的。 – boomboomboom
您忘記清除您購買的清單上的名稱。如果你只添加元素,一旦你添加重複項,你將永遠呆在那裏 –