为什么说方法 nextInt 未定义,大小写"A"是类型未匹配错误


public static void main(String[] args) {
    // TODO Auto-generated method stub
    char packageLetter = 0;
    int totalHours, regularHours, additionalHours=0;
    double monthlyFee, additionalHoursFee, totalFee;
    String input;
    Scanner keyboard = new Scanner(System.in);
    System.out.print("Enter the your's package (A, B, or C)");
    System.out.print("How many hours did you used?");
    totalHours = input.nextInt();
    switch(packageLetter)
    {
    //it says I have a miss match error here
    case "A" :
        monthlyFee = 9.95;
        regularHours = 10;
        additionalHoursFee = additionalHours * 2;
        totalFee = monthlyFee + additionalHoursFee;
        System.out.print("The charges are $: " + totalFee);
        System.out.print("With package B you would have saved" + (totalFee - 13.95));
    break;
    }
}

这里有多个问题。 首先,你的台词说

totalHours = input.nextInt()

应该改为

totalHours = keyboard.nextInt()

其次,您永远不会读取包类型的任何用户输入,因此packageLetter始终0

但是与您看到的特定错误相关的问题是,您的switch语句正在打开packageLetter,这是一个char,但是您的情况在"A"上触发,这是一个String。 这些需要是相同的数据类型,因此您需要将packageLetter更改为String,或者更改大小写以表示:

case 'A': // <-- Notice the single quotes

在Java中,"A"是一个String,但'A'是一个char

您的代码存在几个问题:

  • 您将input声明为 String ,但从未为其分配任何值,因此它null
  • String没有nextInt()方法,该方法来自Scanner
  • 您实际上并没有使用 Scanner 对象。我相信你认为:keyboard.nextInt()
  • switch语句抱怨,因为您没有定义default案例
  • 此外,packageLetter是一个char,你试图将其与String相匹配 - 在Java中,'A'是一个char"A"是一个String

因为packageLetter是单个字符,所以您需要对文字使用单引号:

...
switch(packageLetter)
{
case 'A' :  // Note single quotes.
...

这应该可以修复类型不匹配错误,但您也需要修复奥斯卡·洛佩斯(Óscar López(指出的要点才能使代码正常工作。

相关内容

最新更新