如何在忽略区分大小写的情况下将1D char数组的内容与2D char数组进行比较?

时间:2018-01-31 16:39:44

标签: java arrays multidimensional-array 2d

说我的1D char数组看起来像:

  

[E,A,D,C,C]

和我的2D char数组看起来像:

  

[[E,A,D,B,C],[d,a,d,e,c],[b,a,,e,a]]

这是我尝试做的事情:

public void calculateStatistics(char [] correctAnswers, String [] studentName, char [][] studentAnswers, int fillLvl2, int fillLvl3)
{
    int [] marks = new int [3];
    double average = 0; 
    int totalSum = 0;
    int sum;
    for(int row = 0; row < correctAnswers.length; row++)
    {
        sum = 0; 
        for(int col = 0; col < studentAnswers.length; col++)
        {
            if(studentAnswers[row][col].equals(correctAnswers[col]))
            {
                sum++; 
                totalSum += totalSum;
            }
        }
        marks[row] = sum;
    }
}

4 个答案:

答案 0 :(得分:0)

如果我理解正确,您可以更改将两个字符串进行比较的代码部分:

String studentAnswer = String.valueOf(studentAnswers[row][col]);
String correctAnswer = String.valueOf(correctAnswers[col]);
if(studentAnswer.equalsIgnoreCase(correctAnswer))
{
    sum++; 
    totalSum += totalSum;
}

答案 1 :(得分:0)

要使用字符,并避免任何AutoBoxing to Character或String,您可以使用这样的辅助方法:

static final int convertToLower = 'a' - 'A'; 
boolean isCharEqualsIgnoreCase(char c1, char c2) {
    if (c1 <= 'Z')
        c1 += convertToLower;
    if (c2 <= 'Z')
        c2 += convertToLower;
    return c1 == c2;
}

测试用例:

isCharEqualsIgnoreCase('a', 'a'); // true
isCharEqualsIgnoreCase('A', 'A'); // true
isCharEqualsIgnoreCase('a', 'A'); // true
isCharEqualsIgnoreCase('A', 'a'); // true
isCharEqualsIgnoreCase('A', 'b'); // false

或者,使用自动装箱:一个例子是

char c = 'c';
char C = 'C';

Character.valueOf(c).toString().equalsIgnoreCase(Character.valueOf(C).toString());

答案 2 :(得分:0)

要将字符转换为小写,请使用t方法。您的if语句将如下所示:

Character.toLowerCase()

您的代码将如下所示(在函数之外):

if(Character.toLowerCase(studentAnswers[row][col]) == correctAnswers[col])

节目输出:

char [] correctAnswers = {'a','b','c','a','b','c'};
String [] studentName = {"Sam", "Cathy", "Jensen"};
char [][] studentAnswers = {{'d','B','c','a','b','c'},
                            {'a','a','a','a','b','a'},
                            {'c','b','a','A','B','C'}};
int [] marks = new int [3];
double average = 0; 
int totalSum = 0;
int sum;
for(int row = 0; row < studentAnswers.length; row++)
{
    sum = 0; 
    for(int col = 0; col < correctAnswers.length; col++)
    {
        if(Character.toLowerCase(studentAnswers[row][col]) == correctAnswers[col])
        {
            sum++; 
            totalSum += totalSum;
        }
    }
        marks[row] = sum;
        System.out.println("Students Mark: " + marks[row]);
    }

答案 3 :(得分:0)

以不区分大小写的方式比较字符的最简单方法是:

Character.toLowerCase(c1) == Character.toLowerCase(c2)

或者你可以这样做:

(c1 == c2) || (Character.isLowerCase(c1) ? (c1 == Character.toLowerCase(c2)) : (c1 == Character.toUpperCase(c2)))

你的错误是你试图调用equals,这是一个对象的方法,你打算比较的字符不是对象,它们是原始变量。