制定一个程序,询问产品代码,产品数量,并总结所有价格

时间:2013-10-07 03:55:52

标签: java arrays swing loops compiler-errors

我一直很难做到这一点,我一直在寻找关于如何编码的想法,但我仍然是初学者。这是我的源代码。也许你会通过阅读它来获得我的想法。尽管它应该运行得不好。

import javax.swing.JOptionPane;
public class sto
{
    public static void main(String args[])
    {
        char s;
        do
        {
            int pcod=0, qua;
            int[] cod={101, 102, 103, 104, 105, 106, 107, 108, 109, 110};
            double[] pri={1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 0.1};
            double [] sal=new double[10];
            String[] pro={"q", "w", "e", "r", "t", "y", "u", "i", "o", "p"};
            do
            {
                if(pcod>=101||pcod<=110)
                {
                    pcod=Integer.parseInt(JOptionPane.showInputDialog(null,"Enter Product Code:"));
                    for(int i=0;i<10;i++)
                    {
                        if(pcod==cod[i])
                        {
                            qua=Integer.parseInt(JOptionPane.showInputDialog(null,"Enter quantity:"));
                            sal[i]=pri[i]*qua;
                            JOptionPane.showMessageDialog(null,"You bought:\n"+pro[i]+"......"+pri[i]+" Pesos x"+qua);
                        }
                    }
                }
                else
                if(pcod<=101||pcod>=110)
                    JOptionPane.showMessageDialog(null,"INVALID PRODUCT CODE");
                    //some codes here to make you return to enter a product code again.
            }while(pcod!=00);
            for(int d=0;d<10;d++)
                sal[d]=qua;
            JOptionPane.showMessageDialog(null,"Total sales.........."+sal[d]+" Pesos");
            s=JOptionPane.showInputDialog(null,"Shop Again?(Y/N)").charAt(0);
        }
        while(s=='y');
    }
}

2 个答案:

答案 0 :(得分:0)

我认为你的

if(pcod>=101|| pcod<=110)

是错误的,如果你想让pcod在101到110之间,你会想要使用&amp;&amp;。

在进入循环之前,你似乎还没有真正将pcod设置为零以外的其他任何东西?它是否正确? :)

干杯。

答案 1 :(得分:0)

// .. the problem is in the next few lines
for(int d=0;d<10;d++)
    sal[d]=qua;
JOptionPane.showMessageDialog(null,"Total sales.........."+sal[d]+" Pesos");

缺少括号,for循环只包含下一个缩进的代码行。属性dfor循环语句中定义,在循环之外失去焦点(无法在选项窗格中引用/使用)。

要解决此问题,请将{}放在两行(一组括号中以包含两行)。

这会导致下一个问题。

int pcod=0, qua;

此时,pcod0,但qua没有价值。编译器将发出警告might not have been initialized。快速解决方法是给它一个默认值,但这可能不适合应用程序的逻辑。特别是如果在将输入解析为int值时抛出异常。