如何在输入与数组元素匹配的地方打印整行?
请看看我的代码我哪里出错了... :(
package scanner;
import java.util.Arrays;
import java.util.Scanner;
public class EmployeeInformation {
static Scanner sc = new Scanner(System.in);
static String info[][] = {{"09-001", "Ja Gb", "100", "10", },
{"09-002", "Justine", "200", "20", ""},
{"09-003", "Ja Ja", "150", "15", ""}};
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.print(" - MENU -\n");
System.out.print("A. Search Record\nB. Payroll Summary\n------------------\nEnter choice: ");
String choice = null;
choice = sc.nextLine();
if (choice.equalsIgnoreCase("a")) {
System.out.print("Enter Employee #: ");
String EmpNum = sc.nextLine();
SearchRecord(EmpNum);
}
else {
PayrollSummary();
}
}
private static void SearchRecord(String employeeNumber) {
// TODO Auto-generated method stub
String row[] = new String[3];
int i = 0;
while(i <= info.length) {
int j = 0;
while(j <= info.length) {
if(employeeNumber.equals(info[i][j])) {
for (int a = 0; a <= row.length; a++) {
row[a] = info[i][j];
System.out.print(row[a]);
a++;
}
}
else {
System.out.print("Invalid employee number.");
System.exit(0);
}
j++;
}
i++;
}
}
private static void PayrollSummary() {
System.out.println("Employee #:\tEmployee Name\tRate per Hour\tTotal Hours Worked\tGross Pay");
int r = 0;
while ( r <= info.length - 1) {
int c = 0;
while ( c <= info.length ) {
System.out.print(info[r][c] + "\t\t");
if (c == 3) {
System.out.print("\n");
}
c++;
}
r++;
}
//for (int a = 0; a <= info.length -1; a++) {
// Integer.parseInt(info[a][4]) = Integer.parseInt((info[a][3]) * (info[a][4]));
//}
}
}
输入匹配元素时该怎么办?请给我一个提示
最佳答案
看起来您总是将雇员编号作为2d数组中的第一个元素。在这种情况下,您根本不需要嵌套循环:
String[] matchedRow;
for(int i=0; i<info.length; i++)
{
String[] oneRow = info[i];
if(oneRow[0].equals(employeeNumber))
{
matchedRow = oneRow;
break
}
}
for(int i=0; i<matchedRow.length; i++)
{
System.out.println(matchedRow[i]);
}
就是说,在现实生活中,很少有像您这样的数组中有员工记录。您将创建一个
Employee
类,并具有一个List
个Employee
对象。如果
Employee
类使用正确的equals
,hashCode
和toString
实现正确设计,则match方法将非常简单:employee = employeeList.get(employeeList.indexOf(employee));
System.out.println(employee);
//Do whatever with employee