0

一家公司生产 10 种产品。编写 java 程序以将 10 个项目及其价格存储在数组中。如果客户订购了一个项目,您的程序会检查它是否有效,如果它是有效的打印价格

import javax.swing.JOptionPane;

public class ParallelArray3 {

    public static void main(String[] args){

        final int Num =10;
        int [] Item= {101, 110, 210, 220, 300, 310, 316, 355, 405, 410};
        double [] Price= {0.29, 1.23, 3.50, 0.89, 6.79, 3.12, 4.32, 3.6, 8.3, 5.4};

        String ItemId = null;
        while ((ItemId = JOptionPane.showInputDialog(null, "Please enter your Item ID number: ")) != null)
        {
            boolean correct = false;
            for (int x = 0; x < Item.length; ++x)
            {
                if(ItemId.equals(Item[x]))
                {
                    JOptionPane.showInputDialog(null, "Your Item is: " + Item[x] + "\n" + "the price is: " + Price[x], JOptionPane.INFORMATION_MESSAGE);
                    correct = true;
                    break;
                }
            }
            if(! correct)
            {
                JOptionPane.showMessageDialog(null, "item ID not found, try again.", "Not found", JOptionPane.INFORMATION_MESSAGE);
            }
        }
    }
}

预期结果将显示项目编号和价格

实际结果是说每个项目#都是无效的

4

1 回答 1

0

这是因为您正在比较 String 和 Int

   if(ItemId.equals(Item[x]))
    {

应改为

   if(Integer.parseInt(ItemId)==(Item[x]))
    {

最终代码变为

import javax.swing.JOptionPane;

public class ParallelArray3 {
   public static void main(String[] args) {
final int Num =10;
int [] Item= {101, 110, 210, 220, 300, 310, 316, 355, 405, 410};
double [] Price= {0.29, 1.23, 3.50, 0.89, 6.79, 3.12, 4.32, 3.6, 8.3, 5.4};

String ItemId = null;
while ((ItemId = JOptionPane.showInputDialog(null, "Please enter your Item ID number: ")) != null)
{
    System.out.println(ItemId);
    boolean correct = false;
    for (int x = 0; x < Item.length; x++)
    {
        if(Integer.parseInt(ItemId)==(Item[x]))
        {
            JOptionPane.showInputDialog(null, "Your Item is: " + Item[x] + "\n" + "the price is: " + Price[x], JOptionPane.INFORMATION_MESSAGE);
            correct = true;
            break;
        }
    }
    if(!correct)
    {
        JOptionPane.showMessageDialog(null, "item ID not found, try again.", "Not found", JOptionPane.INFORMATION_MESSAGE);
          }
       }
    }
 }

看下面的截图

于 2019-03-29T20:42:24.513 回答