java - 有人可以解释这段代码中的布尔重复方法吗?
问题描述
这下的代码已经完成,但我无法理解布尔重复字符的功能,为什么 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 这些单词只是为了填充单词数字呵呵
解决方案
此函数检查重复字符的字符串。例如,假设我们有一个字符串
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'。
推荐阅读
- c# - 使用多个 where 的实体框架 Linq 查询
- android - Web 身份验证:无法使用指纹进行身份验证
- python - 没有多索引返回的 Pandas 数据透视表
- flutter - Flutter Stepper 最后一步没有完全滚动
- gradle - 内部 API 构造函数 DefaultDomainObjectSet(Class
) 已被弃用。这计划在 Gradle 7.0 中删除 - java - 使用 Java 流转换具有多个 if/else 的经典嵌套循环
- javascript - 可选的链接逻辑
- python - 在模板中返回 ManyRelatedManager 值
- c++ - 在 C++ 中,如果文件不存在,如何安全地创建文件,但如果文件存在则不打开它?
- reactjs - Context 的 Provider 默认值函数被调用,而不是 Provider 内部的函数