-1

我是一名基础编程学生,我需要有关如何制作特定程序的帮助。场景是:人们进出事件,我需要跟踪他们。允许的人数限制为100人。人们可以单独或集体来。随着人们进出,总数应该会发生变化。达到限制后应拒绝人们访问。

一切都将进入 JOptionPane。

不确定我是否正在寻找最好的网站寻求帮助,但任何建议都会有所帮助。

我知道我会为此做一个while循环。

import javax.swing.JOptionPane;
public class HwTwoPt2 {

    public static void main(String[] args) {
        int enter, exit, total;
         int maxCapacity = 106;
         int count = 0;
         int groupAmt = 0;


         while(count != maxCapacity){
            groupAmt = Integer.parseInt(JOptionPane.showInputDialog("Enter total amount in the group: "));


             }
         }

    }
4

2 回答 2

0

如果您想在达到限制后拒绝人们访问,您需要将您的 while 循环更改为:

while(count < maxCapacity)

如果您使用 != maxCapacity,则 107 的值将通过并允许人们进入。

您还需要在将 groupAmt 添加到 maxCapacity 之前对其进行验证。

if((count + groupAmt) < maxCapacity)
{
    count += groupAmt;
}
于 2013-10-07T21:57:54.957 回答
0

我建议您将所有这些封装到一个对象中。Java 是一种面向对象的语言。最好尽早习惯于封装和信息隐藏方面的思考。

像这样的东西:

public class CapacityTracker {
    private static final int DEFAULT_MAX_CAPACITY = 100;
    private int currentCapacity;
    private int maxCapacity;

    public CapacityTracker() { 
        this(DEFAULT_MAX_CAPACITY);
    }

    public CapacityTracker(int maxCapacity) { 
        this.maxCapacity = ((maxCapacity <= 0) ? DEFAULT_MAX_CAPACITY : maxCapacity);
        this.currentCapacity = 0;
    }

    public int getCurrentCapacity() { return this.currentCapacity; }

    public void addAttendees(int x) { 
        if (x > 0) {
            if ((this.currentCapacity+x) > this.maxCapacity) {
                throw new IllegalArgumentException("max capacity exceeded");
            } else {
                this.currentCapacity += x;
            }         
        }
    }
}

我会不断添加方法以使我更方便地使用它。

我也可以创建一个自定义的 CapacityExceededException。

于 2013-10-07T22:00:30.800 回答