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();
}
}
文字列を次の==
ように比較しないでください:
comparison[i] != employeeName[j]
equals()
代わりに使用する:
!comparison[i].equals(employeeName[j])
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加