gpt4 book ai didi

java - 如何知道数组是否包含给定的值

转载 作者:行者123 更新时间:2023-11-30 05:51:22 25 4
gpt4 key购买 nike

你好,我想弄清楚数组是如何工作的,现在我创建了一个在类中查找整数的类,但我想我已经做了一些工作..尤其是我认为转换方法是错误的..它如果数组索引包含该值,则必须在数组中搜索,如果是,则打印出来但它不起作用有人可以解释逻辑以及如何解决它吗? (如果可能的话,举个例子)

提前致谢!下面你可以看到我的代码:

package h05UitgeschrevenGetal;

import java.awt.event.*;
import java.util.Random;

import javax.swing.*;

public class GetalConverter extends JPanel implements ActionListener {

private JLabel getal;
private JTextField invoer, uitvoer;
private int invoerWaarde;
private JButton converteer;

String[] klein = new String[20];
String[] groot = new String[10];

public GetalConverter() {

getal = new JLabel("geef een geheel getal");
add(getal);

invoer = new JTextField(7);
invoer.addActionListener(this);
add(invoer);

converteer = new JButton("In woorden");
converteer.addActionListener(this);
add(converteer);

uitvoer = new JTextField(7);
uitvoer.setEditable(false);
add(uitvoer);

klein[0] = "nul";
klein[1] = "een";
klein[2] = "twee";
klein[3] = "drie";
klein[4] = "vier";
klein[5] = "vijf";
klein[6] = "zes";
klein[7] = "zeven";
klein[8] = "acht";
klein[9] = "negen";
klein[10] = "tien";
klein[11] = "elf";
klein[12] = "twaalf";
klein[13] = "dertien";
klein[14] = "veertien";
klein[15] = "vijftien";
klein[16] = "zestien";
klein[17] = "zeventien";
klein[18] = "achtien";
klein[19] = "negentien";

groot[1] = "tien";
groot[2] = "twintig";
groot[3] = "dertig";
groot[4] = "veertig";
groot[5] = "vijftig";
groot[6] = "zestig";
groot[7] = "zeventig";
groot[8] = "tachtig";
groot[9] = "negentig";

}

public void setValue(int val) {

invoerWaarde = val;
//System.out.println(invoerWaarde);
}

public int getValue() {

return invoerWaarde;

}

public void convert() {

// here comes the converting code

}

@Override
public void actionPerformed(ActionEvent e) {

setValue(Integer.parseInt(invoer.getText()));
convert();
//System.out.println(invoerWaarde);


}

}

最佳答案

您已将数组定义为:-

String[] strings = new String[klein];

现在,当您调用 contains 方法时:-

Arrays.asList(strings).contains(waar)

您实际上是在检查 String 类型的 ArrayList 中是否包含整数。因为 waar 是您在 convert 方法中传递的整数。您如何期望它返回 true 值?

it has to search in the array if the array index contains that value

对于这种情况,您需要将该 传递给您的convert 方法。您宁愿传递 index

我猜你想要这样的东西:-

public void convert(String value) {

for (int i = 0; i < strings.length; i++) {
if (strings[i].equals(value)) {

System.out.println("Value: " + strings[i]);
System.out.println("Index: " + i);
}
}

}

关于java - 如何知道数组是否包含给定的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12876223/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com