簡體   English   中英

Java錯誤消息

[英]Java error message

我對使用Java程序進行類學習時遇到的錯誤消息感到困惑,

 ----jGRASP exec: javac -g Program3.java

Program3.java:26: error: incompatible types
    productNum = input.nextInt();
                              ^
  required: int[]
  found:    int
1 error

 ----jGRASP wedge2: exit code for process is 1.
 ----jGRASP: operation complete.

錯誤消息參考如下:

import javax.swing.*;
import java.util.Scanner;

public class Program3
{
public static void main(String[] args)
{
    final int NUMBER_OF_ITEMS = 5;
    int[]productNum = {1,2,3,4,5};   //array of product numbers
    double[]price = {2.98, 4.50, 9.98, 4.49, 6.87};   //array of
            price
    double quantity, product, total;
    Scanner input = new Scanner(System.in);
    System.out.print("Enter Product Number (1-5) or -1 to Quit:");
    productNum = input.nextInt();
            System.out.print("Enter Quantity:");
    quantity = input.nextDouble();
    total = product*quantity;
    System.out.print(total);
}
}

您的代碼中存在許多錯誤。 第一個是不能將數組的值設置為整數,需要指定一個索引,例如: productNum[0] = input.nextInt();

嘗試使用以下代碼替換現有的main功能:

public static void main(String[] args)
{
    int product;
    System.out.print("Enter Product Number (1-5) or -1 to Quit:");
    Scanner input = new Scanner(System.in);
    product = input.nextInt();
    while(product != -1)
    {
        final int NUMBER_OF_ITEMS = 5; //This isn't being used for anything and could be removed
        int[] productNum = {1,2,3,4,5}; //This also isn't really being used for anything and could be removed
        double[] price = {2.98, 4.50, 9.98, 4.49, 6.87};
        double quantity, total;
        System.out.print("Enter Quantity:");
        quantity = input.nextDouble();
        total = price[product - 1] * quantity;
        System.out.println(total + "\n");
        System.out.print("Enter Product Number (1-5) or -1 to Quit:");
        product = input.nextInt();
    }
}

您正在將整數分配給整數數組。 就像在做

String lol = "random text";
int random = lol;

這將引發錯誤,因為整數不能容納字符串的值。 您的情況也一樣。 您試圖將整個數組的值設置為單個int的值。 也許productNum[0] = input.nextInt(); 這樣,您可以將數組內部的int值設置為int。 您將必須編寫一個for循環,以便您可以填充數組中比數字0更多的元素,但是在我看來,這樣做並不難。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM