【问题标题】:Im using JOptionPane and I'm not sure why its not working when I try to enter the Item Id for the first "?" it asks in my code我正在使用 JOptionPane,但我不确定为什么当我尝试为第一个“?”输入项目 ID 时它不起作用。它在我的代码中询问
【发布时间】:2019-03-29 20:24:59
【问题描述】:

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

预期结果将显示商品编号和价格

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

【问题讨论】:

  • 你调试过吗?你检查过if(ItemId.equals(Item[x]) 是否真实吗?

标签: java arrays joptionpane parallel-arrays


【解决方案1】:

这是因为你在比较 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);
          }
       }
    }
 }

【讨论】:

  • @Kale_Kyle 如果你同意这个答案标记它(向上箭头)/接受它作为正确答案
猜你喜欢
  • 1970-01-01
  • 2014-04-23
  • 2022-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多