請幫助我理解為什么我寫的布爾方法沒有正確返回。我要求用戶輸入一系列要存儲在檢查重復項的數組中的整數。import java.util.Scanner;public class PokerHands { public static void main(String args[]) { System.out.println(containsPair(welcome())); } // end main private static int[] welcome() { Scanner read = new Scanner(System.in); int[] poker_array = new int[5]; System.out.println("Enter five numeric cards, no face cards. Use 2-9: "); for (int i = 0; i < 5; i++) { System.out.printf("Card %d: ", i + 1); int nums = read.nextInt(); while (nums < 2 || nums > 9) { System.out.println("Wrong input. Choose from 2-9 only: "); nums = read.nextInt(); } // end while poker_array[i] = nums; } for (int i = 0; i < poker_array.length; i++) { System.out.print(poker_array[i] + ", "); } return poker_array; } // end welcome() private static boolean containsPair(int hand[]) { for (int i = 0; i < hand.length; i++) { for (int j = 0; j < hand.length; j++) { if (hand[i] == hand[j]) { return true; } // end if } // end inner for } // end outer for return false; } // end containsPair()} //end class輸出:$ java PokerHands輸入五張數字卡片,沒有人臉卡片。使用 2-9:卡片 1:2卡片 2:3卡片 3:4卡片 4:5卡片 5:62, 3, 4, 5, 6, 真$ java PokerHands 輸入五張數字牌,無面牌。使用 2-9:卡片 1:2卡片 2:2卡片 3:3卡片 4:4卡片 5:52, 2, 3, 4, 5, 真$ java PokerHands輸入五張數字卡片,沒有人臉卡片。使用 2-9:卡片 1:2卡片 2:2卡片 3:2卡片 4:2卡片 5:22, 2, 2, 2, 2, 真
3 回答

白板的微信
TA貢獻1883條經驗 獲得超3個贊
使用 HashSet 更改方法。代碼將是這樣的
private static boolean containsPair(int hand[])
{
//adding to list all elements
List<Integer> intList = new ArrayList<>();
for (int i : hand) {
intList.add(i);
}
//put all elements to set
HashSet<Integer> zipcodeSet = new HashSet<>(intList);
//if size not match , has a dublicate
return zipcodeSet.size() != hand.length;
} // end containsPair()
添加回答
舉報
0/150
提交
取消