只能检查我的数组的第一个元素

时间:2016-10-10 00:19:15

标签: c++ arrays

我遇到一些问题,让我的数组在我的for循环中迭代。 此功能的目的是检查数字是否已经放入其他地方的数组中,因此不会出现重复项。 当我运行该函数时,它只遍历函数的第一个元素并停止。

bool check(int wins[], int number)
{   
    for (int i = 0; i <= arraySize; ++i)
        if (number == wins[i])
        {
            return  true;
        }
        else if (number != wins[i])
        {
            return false;
        }

}

我真的很感激帮助。

1 个答案:

答案 0 :(得分:3)

你的缩进是误导。这里发生了什么:

bool check(int wins[], int number)
{   
    for (int i = 0; i < arraySize; ++i)   // assuming that arraySize is some const size of the array
        if (number == wins[i])   // if number is found 
        {
            return  true;        // return immediately  
        }

    // if you arrive here, the loop finished without a match
    return false;
}

所以在第一次迭代中,你或者数字等于元素或者它是不同的,但是在这两种情况下你都返回并且函数完成了!

如果您想搜索您的项目,您需要做一些小改动:

public class ImageViewer extends JFrame {

public ImageViewer() {
    //create panel of actions
    JPanel actionPanel = new JPanel();
    actionPanel.setLayout(new GridLayout(1, 4));

    actionPanel.add(new JButton("Prev"));
    actionPanel.add(new JButton("Add"));
    actionPanel.add(new JButton("Del"));
    actionPanel.add(new JButton("Next"));


    //Create panel to hold pictures
    JLabel label= new JLabel(new ImageIcon("C:/Users/Madison/Desktop/capture.png"), JLabel.CENTER);
    JPanel imagePanel = new JPanel(new BorderLayout());
    imagePanel.add(label, BorderLayout.CENTER );

    //Add contents to frame
    add(imagePanel, BorderLayout.NORTH);
    add(actionPanel, BorderLayout.SOUTH);
}

public static void main (String args []){
    ImageViewer frame = new ImageViewer();
    frame.setTitle("Title");
    frame.setSize(1000, 500);
    frame.setLocationRelativeTo(null);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
}