亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

布爾方法不斷返回真

布爾方法不斷返回真

開心每一天1111 2021-08-25 18:10:53
請幫助我理解為什么我寫的布爾方法沒有正確返回。我要求用戶輸入一系列要存儲在檢查重復項的數組中的整數。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貢獻1891條經驗 獲得超3個贊

這是因為對于 1st pass,i=0j=0. 所以它總是會返回true。你應該初始化j=i+1


查看完整回答
反對 回復 2021-08-25
?
MMMHUHU

TA貢獻1834條經驗 獲得超8個贊

嘗試將布爾值中的 if 更改為以下內容:

if (hand[i] == hand[j] && i != j)


查看完整回答
反對 回復 2021-08-25
?
白板的微信

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()


查看完整回答
反對 回復 2021-08-25
  • 3 回答
  • 0 關注
  • 170 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號