【问题标题】:programing advice for a class example类示例的编程建议
【发布时间】:2013-10-07 21:49:50
【问题描述】:

我是一名基础编程学生,我需要有关如何制作特定程序的帮助。 场景是:人们进出事件,我需要跟踪他们。允许的人数限制为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: "));


             }
         }

    }

【问题讨论】:

  • 为什么它必须进入 JOptionPane?这段代码没有编写任何内容。最好使用纯文本界面,直到逻辑正确,然后添加 GUI。你犯了一个经典的新编程错误:把所有东西都放在一个 main 方法中。将其封装成一个可以测试和重用的对象。
  • 您面临的问题是什么?您能否就您遇到的问题向我们提供更多信息?

标签: java swing loops joptionpane


【解决方案1】:

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

while(count < maxCapacity)

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

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

if((count + groupAmt) < maxCapacity)
{
    count += groupAmt;
}

【讨论】:

    【解决方案2】:

    我建议您将所有这些封装到一个对象中。 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。

    【讨论】:

    • 我曾考虑过使用对象,但对它们不是很熟悉。但我要求使用它们,他说不。显然它的进步...... -_- @duffymo
    • 也许有一天。现在你什么都没有。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-13
    • 1970-01-01
    • 2012-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多