我正在使用JOptionPane,当我尝试输入第一个“?”的项目ID时,我不确定为什么它不起作用,它在我的代码中询问

问题描述 投票:0回答:1

一家公司生产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);
            }
        }
    }
}

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

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

java arrays joptionpane parallel-arrays
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);
          }
       }
    }
 }

see screenshot below

© www.soinside.com 2019 - 2024. All rights reserved.