gpt4 book ai didi

java - 打印输入与数组元素匹配的整行

转载 作者:行者123 更新时间:2023-11-30 11:40:19 25 4
gpt4 key购买 nike

如何打印输入与数组元素匹配的整行?请查看我的代码,我哪里出错了...:(

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]));

//}
}
}

当input匹配到某个元素时怎么办?请给我一个提示

最佳答案

看起来您总是将员工编号作为二维数组中的第一个元素。在这种情况下,您根本不需要嵌套循环:

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 类并拥有一个包含 Employee 对象的 List。如果 Employee 类的设计正确且具有 equals 的正确实现, hashCodetoString ,匹配方法将非常简单:

employee = employeeList.get(employeeList.indexOf(employee));
System.out.println(employee);
//Do whatever with employee

关于java - 打印输入与数组元素匹配的整行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12805833/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com