我在网上搜索如何转换数组中的两个特定元素,并且对于研究非常不吉利
package scanner;
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 if (choice.equalsIgnoreCase("b")){
PayrollSummary();
}
else {
System.out.print("Invalid input.");
}
}
private static void SearchRecord(String employeeNumber) {
// TODO Auto-generated method stub
String[] matchedRow = null;
for (int i = 0; i < info.length; i++) {
String[] oneRow = info[i];
if (oneRow[0].equals(employeeNumber)) {
matchedRow = oneRow;
break;
}
}
System.out.print("\nEmployee #:\tEmployee Name\tRate per Hour\tTotal Hours Worked\n");
for (int i = 0; i < matchedRow.length; i++) {
System.out.print(matchedRow[i] + "\t\t");
}
}
private static void PayrollSummary() {
System.out.println("\nEmployee #:\tEmployee Name\tRate per Hour\tTotal Hours Worked\tGross Pay");
int intArr[] = new int[info.length];
int r = 0;
while ( r < info.length) {
int c = 0;
while ( c <= r ) {
if ( c == 2 ) {
intArr[c] = Integer.parseInt(info[r][c]);
if ( c == 3 ) {
intArr[c] = Integer.parseInt(info[r][c]);
}
}
c++;
// How do I multiply index 2 and 3 of Array info and store it in info[r][4]?
}
r++;
}
}
}
...
答案 0 :(得分:4)
为了将两个表示为字符串的值相乘,您必须先解析它们。
如果要将任意String解析为Integer,您应该记住,不可能解析某些字符串,例如“Justine”。您必须处理在这种情况下将抛出的NumberFormatException。
try{
Integer myInt = Integer.parseInt(info[x][y]);
}catch(NumberFormatException e){
// handle your exception
}
答案 1 :(得分:0)
你可以这样做
class Testing
{
public static void main(String[] args)
{
System.out.println(isNumeric("123"));
System.out.println(isNumeric("123.45"));
System.out.println(isNumeric("$123"));
System.out.println(isNumeric("123x"));
}
public static boolean isNumeric(String str)
{
try
{
double d = Double.parseDouble(str);
}
catch(NumberFormatException nfe)
{
return false;
}
return true;
}
}
通过这种方式,您可以解析数组,如果它是NumberFormatException,则它不是数字。