首页 > 解决方案 > 有人可以解释这段代码中的布尔重复方法吗?

问题描述

这下的代码已经完成,但我无法理解布尔重复字符的功能,为什么 I !=... 以及 str.lastIndexOf(str.charAt(i) 是什么,如果您为我解释,将不胜感激。

import java.awt.event.*;
import javax.swing.*;
class SimplApp extends JFrame implements ActionListener {
     //JTextField
    static JTextField t;

    // JFrame
    static JFrame f;

    // JButton
    static JButton b;

    // label to display text
    static JLabel l;

    // default constructor
    SimplApp() {

    }

    static boolean duplicatecharacters(String str)
    {
        for(int i=0;i<str.length();i++)
        {
            if(i!=(str.lastIndexOf(str.charAt(i))))
                return true;
        }
        return false;
    }

    // main class
    public static void main(String[] args)
    {
        // create a new frame to store text field and button
        f = new JFrame("textfield");

        // create a label to display text
        l = new JLabel("nothing entered");

        // create a new button
        b = new JButton("submit");

        // create a object of the text class
        SimplApp te = new SimplApp();

        // addActionListener to button
        b.addActionListener(te);

        // create a object of JTextField with 16 columns
        t = new JTextField(16);

        // create a panel to add buttons and textfield
        JPanel p = new JPanel();

        // add buttons and textfield to panel
        p.add(t);
        p.add(b);
        p.add(l);

        // add panel to frame
        f.add(p);

        // set the size of frame
        f.setSize(300, 300);

        f.setVisible(true);
    }

    // if the button is pressed
    public void actionPerformed(ActionEvent e)
    {
        String s = e.getActionCommand();
        if (s.equals("submit")) {
            boolean b=SimplApp.duplicatecharacters(t.getText());
            // set the text of the label to the text of the field
            if(b==true)
                l.setText("It has duplicates");
            else
                l.setText("It doesn't have duplicates");

            // set the text of field to blank
            //t.setText(" ");
        }
    }
}

所以我只想知道函数是如何工作的,为什么他们使用 != 编写函数,因为该函数用于查找重复输入不应该像 string.length 为 4 那样,并使用 for 循环搜索向下1 乘 1,如果其中一个数字等于另一个数字,则在下面返回 true 这些单词只是为了填充单词数字呵呵

标签: javauser-interface

解决方案


此函数检查重复字符的字符串。例如,假设我们有一个字符串

String str = "abcdaf"

for 循环遍历字符串的长度。索引 ->

0 -> a
1 -> b
2 -> c
3 -> d
4 -> a
5 -> f

因此,在迭代函数时,会像这样检查 ->

if(i != str.lastIndexOf(str.charAt(i)))

让我们取索引 0。

// str = "abcdaf"
str.charAt(0) // returns 'a'
str.lastIndexOf('a') // returns 4

0 != 4 表示字符串中有多个 'a'。


推荐阅读