回 帖 发 新 帖 刷新版面

主题:请教一个关于JAVA 里 STACK 的程序

stack没学好...

题目:由用户输入任意个动物的名称和重量存储在stack. 然后输出体重小于20kg的动物名称和重量.(JAVA)

这里需要定义2个stack吗?一个放名字,另一个放体重,还是可以用一个stack?如果用一个stack 又要如何来比较体重呢?

这样写对吗?

import javax.swing.*;
public class animal
{
    public static void main(String srgs[])
    {
        String output="animal information:\n\nName\tWeight\n\n";
        int counter=0;
        String name[]=new String[100];
        double weight[]=new double[100];

        name[counter]=JOptionPane.showInputDialog("Enter animal name "+(counter+1)+": ");
        weight[counter]=Double.parseDouble(JOptionPane.showInputDialog("Enter animal weight "+(counter+1)+": (Enter -1 to Exit!)"));
        while(weight[counter]!=-1)
        {
            counter++;
            name[counter]=JOptionPane.showInputDialog("Enter animal name "+(counter+1)+": ");
            weight[counter]=Double.parseDouble(JOptionPane.showInputDialog("Enter animal weight "+(counter+1)+": (Enter -1 to Exit!)"));
        }

        Stack anime=new Stack();

        for(int i=0;i<=counter;i++)
        {
            stack.push(name[i]);
            stack.push(weight[i]);
        }

        for(int i=counter;i=0;i--){
            if(weight[i]<20)
                if(weight[i]!=-1) output+=stack.pop()+"\t"+stack.pop();
            else
            {
                stack.pop();
                stack.pop();
            }
        }

        JTextArea output1=new JTextArea();
        output1.setText(output);
            JOptionPane.showMessageDialog(null,output1);

            System.exit(0);
    }
}

回复列表 (共1个回复)

沙发

name 和 weight应该是animal的属性啊

应该这么写
public class animal{
    String[] name;
    double[] weight;
}

对不对你运行一下,看结果

我来回复

您尚未登录,请登录后再回复。点此登录或注册