我正在尝试编写一个程序来检查2名员工的工资。因此,我首先接受名为employeeName的数组中的所有员工的名称以及名为AnnualSales的数组中的员工的销售额。 当我尝试使用存储在employeeName数组中的名称检查用户输入的名称时,我遇到了问题。
import java.util.Scanner;
public class Array {
public static void main(String[] args) {
int numberOfEmployees; // will store the number of employees
int compare; // number of employees you want to compare results to
//Scanner class enables user input
Scanner sp = new Scanner(System.in);
System.out.println("Enter the number of employees: ");
numberOfEmployees = sp.nextInt();
String[] employeeName = new String[numberOfEmployees]; // this string array will store the name of employees
double[] AnnualSales = new double[numberOfEmployees]; // this will store the sales of every individual employee
这将存储所有employeeNames及其AnnualSales。
for(int i = 0 ; i < numberOfEmployees ; i++) {
System.out.printf("Enter name of employee %d: ",i+1);
employeeName[i] = sp.next();
System.out.printf("Enter salary of employee %d: ",i+1);
AnnualSales[i] = sp.nextDouble();
}
System.out.println("Enter the number of employees you want to compare records of: ");
compare = sp.nextInt();
if(compare > numberOfEmployees) {
System.out.println("IndexOutOfBound");
System.exit(0);
}
String[] comparison = new String[compare];
for(int i = 0; i < compare; i++) {
System.out.printf("Enter name of employee %d for comparison: ",i+1);
comparison[i] = sp.next();
// a loop to go through all the names in the employeeName array
System.out.println(comparison[i]);
我只想检查员工的姓名是否已经在employeeName数组中。下面的 if 条件在比较employeeName数组中的第一个名称时退出,但我想检查一个特定员工的名字,其中包含employeeName数组中的所有员工。
for(int j = 0 ; j < numberOfEmployees ; j++) {
if(comparison[i] != employeeName[j]) {
System.out.println("Employee does not exist!");
System.exit(0);
}
}
}
// compare salary of 2 employees
if(AnnualSales[compare-1] > AnnualSales[compare-2]) {
System.out.printf("Sales of %s are greater than %s",employeeName[compare-1], employeeName[compare-2]);
}else {
System.out.printf("Sales of %s are less than %s",employeeName[compare-1], employeeName[compare-2]);
}
sp.close();
}
}
答案 0 :(得分:0)
不要将字符串与==
进行比较,如下所示:
comparison[i] != employeeName[j]
改为使用equals()
:
!comparison[i].equals(employeeName[j])
答案 1 :(得分:0)
You need to correct this as:
for(int j = 0 ; j < numberOfEmployees ; j++) {
if(!comparison[i].equals(employeeName[j])) {
System.out.println("Employee does not exist!");
System.exit(0);
}
}
}
**Output after changing this condition of your code:**
Enter the number of employees:
3
Enter name of employee 1: a
Enter salary of employee 1: 1
Enter name of employee 2: b
Enter salary of employee 2: 2
Enter name of employee 3: c
Enter salary of employee 3: 3
Enter the number of employees you want to compare records of:
2
Enter name of employee 1 for comparison: a
a
Employee does not exist!