简体   繁体   English

Java中的Int和String数组

[英]Int and String array in Java

public class CHECK {
public CHECK(){
    String []wrkrs = {"Денис", "Саша", "Наталья", "Анатолий", "Юра", "Коля", "Катя", "Дима", "Антон","Тамара"};
    int [] wrkrsPhone = {22626,22627,22628,22629,22630,22631,22632,22633,22634,22635};
    String a = JOptionPane.showInputDialog(null, "Hello,friend!Do you wanna know, is that guy at work?Enter name:");


    if(Arrays.asList(wrkrs).contains(a)){
        JOptionPane.showMessageDialog(null, "That guy is at work!");
        JOptionPane.showMessageDialog(null, "calling " + wrkrsPhone[wrkrsPhone.toString().indexOf(a)]);
    }else{
        JOptionPane.showMessageDialog(null, "Такого сотрудника нет!");
    }
}

I have two arrays, which contain ints and strings. 我有两个数组,其中包含整数和字符串。 As you can see, I want to add the number of elements in the string array (for example, wrkrs number 3) to the int array, called wrkrs phone. 如您所见,我想将字符串数组中的元素数量(例如wrkrs number 3)添加到称为wrkrs phone的int数组中。 How can i do it? 我该怎么做? I tried IndexOf, but it doesn't work. 我尝试了IndexOf,但是它不起作用。

The output, i want is something like: 我想要的输出是这样的:

Enter name:
Юра
That guy is at work!
Calling Юра + wrkrsPhone(Юра).

A better solution would be to have a Worker class that would contain the worker's name and their phone number. 更好的解决方案是使Worker类包含工作者的姓名和电话号码。

Then you can use a HashMap<String,Worker> instead of your arrays to store the data. 然后,您可以使用HashMap<String,Worker>代替数组来存储数据。

This makes the search more efficient : 这使搜索更加有效:

Map<String,Worker> workersMap = new HashMap<>();
workersMap.put ("Денис", new Worker ("Денис", 22626));
...
Worker worker = workersMap.get(a);
if (worker != null) {
    call (worker.getPhone()); // or do whatever you want to do with the phone number
}

This is more efficient than Arrays.asList(wrkrs).contains(a) , which performs linear search on the List. 这比Arrays.asList(wrkrs).contains(a)效率更高,后者在List上执行线性搜索。

...
List list = Arrays.asList(wrkrs);
if(list.contains(a)){
    JOptionPane.showMessageDialog(null, "That guy is at work!");
    JOptionPane.showMessageDialog(null, "calling " + wrkrsPhone[list.indexOf(a)]);
}
...

U better use a Map or extract a class Contact which have name and phone property but i think this is what u looking for :) U最好使用Map或提取具有namephone属性的Contact类,但我认为这是您要寻找的:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM