如何使用字符串搜索数组以显示相应的数字?我的任务要求我们让用户输入一个名字,然后让他们相应的工资得到它,这是我到目前为止的代码,我不知道该怎么用来做这个
import java.io.*;
public class Employees {
public static void main(String agrs[]) throws IOException {
BufferedReader keyboardInput = new BufferedReader(new InputStreamReader(System.in));
double pay;
String name;
String answer;
//Arrays
double[] employeePay = new double[3];
String[] employeeName = new String[3];
pay = employeePay.length;
//for loops
for (int x = 0; x <= employeePay.length - 1; x++) {
System.out.print("Please enter the employee name:");
employeeName[x] = (keyboardInput.readLine());
System.out.print("Please enter the employe pay :");
employeePay[x] = Double.parseDouble(keyboardInput.readLine());
}
//requesting a name
System.out.println("Please enter an employee name to search for:");
answer = (keyboardInput.readLine());
for (int x = 0; x <= employeePay.length - 1; x++) {
if (employeeName[x].equalsIgnoreCase(answer)) {
System.out.print(employeeName + " pay rate is " + pay);
} else {
System.out.print(" The employee name hasnt been entered");
}
}
}
}
答案 0 :(得分:0)
考虑使用HashMap而不是使用2个单维数组
int employeeCount = 3;
HashMap<String, Double> employeePayMap = new HashMap<String, Double>();
// ... code to capture input
for (int x = 0; x < employeeCount; x++) {
System.out.print("Please enter the employee name:");
String name = (keyboardInput.readLine());
System.out.print("Please enter the employe pay :");
Double pay = Double.parseDouble(keyboardInput.readLine());
employeePayMap.put( name, pay );
}
然后将付款检索为
Double payFound = employeePayMap.get(answer);
将payFound检查为null - 如果为null,则名称不匹配。
答案 1 :(得分:0)
你做错了什么:
if (employeeName[x].equalsIgnoreCase(answer)) {
System.out.print(employeeName + " pay rate is " + pay);
}
在这里打印整个employeeName
,而不是预期的索引。它应该是employeeName[x]
。 pay
也只是employeePay.length
。我不认为你在这里打印employeePay数组的长度。它应该是employeePay[x]
。
if (employeeName[x].equalsIgnoreCase(answer)) {
System.out.print(employeeName[x] + " pay rate is = " + employeePay[x]);
}
更好的方法:
如果您有配对的内容(例如员工姓名和付款),请更好地使用Map
而不是两个离散数组。这是更好,更清洁的方法。
您不仅可以轻松地将数据插入到地图中,还可以从地图中搜索数据,而无需在代码中进行迭代。