【问题标题】:Problems with array changing elements数组更改元素的问题
【发布时间】:2015-03-26 02:15:54
【问题描述】:

我正在尝试使用 Jbutton 将数组中的元素更改为单词“empty”,并且如果数组中选定位置的 为空,则还通过 Jtextfield 添加名称。出于某种原因,我无法让它工作。这是代码,不知道是我遗漏了什么还是我完全错了

move = new JButton("Add Tennant");
window.add(move);
moveIn.addActionListener(this);

Tennant = new JTextField(FIELD_WIDTH);
nTennant.setText("Enter new name") ;
window.add(Tennant);
Tennant.addActionListener(this);

evict = new JButton("Evict");
window.add(evict);
moveIn.addActionListener(this);

不同的方法:

if(e.getSource() == move)
{
    if (occupant[selectedApartment].equals("empty"))
    {
        occupant[selectedApartment] = Tennant.getText();
    }
}

if(e.getSource() == evict)
{
    if(!occupant[selectedApartment].equals("Empty"))
    {
        occupant[selectedApartment] = "Empty";
    }
}

【问题讨论】:

  • 考虑提供一个runnable example 来证明您的问题。这不是代码转储,而是您正在做的事情的一个示例,它突出了您遇到的问题。这将减少混乱并获得更好的响应

标签: java arrays if-statement elements


【解决方案1】:

首先让我跳出来的是你用occupant[selectedApartment] = "Empty"; 设置一个公寓是空的,但是用if (occupant[selectedApartment].equals("empty")) 来测试一个公寓是否是空的

"Empty" != "empty"

你可以改变

if (occupant[selectedApartment].equals("empty"))

if (occupant[selectedApartment].equals("Empty"))

或使用

if (occupant[selectedApartment].equalsIgnoreCase("empty"))

或改变

occupant[selectedApartment] = "Empty";

occupant[selectedApartment] = "empty";

【讨论】:

  • 我使用了 if (occupant[selectedApartment].equalsIgnoreCase("empty")) 并且它有效,但仍在使用 evict 功能
猜你喜欢
  • 2016-08-08
  • 2011-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多