0

我用Java制作了一个字符数组,

char[] letterGrade = { 'A','B','C','D','F'};

我试图引用这样的元素,

letterGrade[0]

我收到一个错误,指出类型不兼容

必需:字符[]

找到:字符

我已经在代码的其他地方用一个双精度数组完成了这个,它工作得很好。为什么它不适用于字符数组?

谢谢!

从您的评论中更新

public static void method()
{
    double totalEarnedPoints = 1;
    double totalPossiblePoints = 1;

    double gradePer = 0.0;
    gradePer = (totalEarnedPoints / totalPossiblePoints);
    char[] letterGrade = { 'A', 'B', 'C', 'D','F'};
    if (gradePer >= gradeScale[0])
    {
        letterGrade = char letterGrade(0);
    }
    else if (calcPercent >= gradeCutoffs[1] && calcPercent < gradeCutoffs[0])
    {
        letterGrade= char letterGrade(1);
    }
}
4

4 回答 4

1

“我正在尝试使用 if 语句来实现它,

char[] letterGrade = { 'A', 'B', 'C', 'D','F'}; 
if (calcPercent >= gradeCutoffs[0]) { 
      letterGrade = letterGrade[0];
}

如果你这样做。因为 letterGrade 是 type char[],所以不能只用 char 分配它。L.H.S.值必须是一个字符。

于 2013-06-15T06:55:45.513 回答
0

The posted sample works if your target variable is of type char, so I assume that you are doing something wrong in the assignment. Maybe you are calling a function which requires a char[] in wich case you should use funct(letterGrade) without the [0].

If your problem persists you should post a bit more code.

Update

I fixed your code to make it compile. of course I don't know what it is supposed to be so I had to make some assumptions, but you should see how the syntax is supposed to be.

public static void method()
{
    double totalEarnedPoints = 1;
    double totalPossiblePoints = 1;
    double gradeScale[] = {1, 2, 3};
    double gradeCutoffs[] = {1, 2, 3};
    double gradePer = 0.0;
    char letter;
    double calcPercent = 1;

    gradePer = (totalEarnedPoints / totalPossiblePoints);
    char[] letterGrade = { 'A', 'B', 'C', 'D','F'};
    if (gradePer >= gradeScale[0])
    {
        letter = letterGrade[0];
    }
    else if (calcPercent >= gradeCutoffs[1] && calcPercent < gradeCutoffs[0])
    {
        letter = letterGrade[1];
    }
    else
        letter = 'F';

    System.out.println("Grade:"+letter);
}
于 2013-06-15T06:48:16.420 回答
0

This works fine for me: char[] letterGrade = { 'A','B','C','D','F'}; System.out.println(letterGrade[0]); It outputs A

So I suspect it is what you are assigning it to. Perhaps somewhere you have: letterGrade = letterGrade[A]

于 2013-06-15T06:48:55.203 回答
0
required: char[]

found: char 

如果您在 char[] 数据类型中分配 char,则会发生这种类型的错误。

前任:

char[] ch = letterGrade[0];
于 2013-06-15T07:07:59.270 回答