【问题标题】:How to use set method in a loop? (Java) [closed]如何在循环中使用 set 方法? (Java)[关闭]
【发布时间】:2017-06-02 22:46:08
【问题描述】:

我是初学者,想知道如何使用循环来更新对象 ArrayList 中的属性。所以这里我有一个智能手机的arraylist,每个智能手机都有serialNo和brand作为属性,但价格还没有更新。

public class Smartphone{
  public String serialNo;
  public String brand;
  public Double price;

  public Smartphone(String serialNo, String brand){
    this.serialNo = serialNo;
    this.brand = brand;
  }

  public void setPrice(double price){
    this.price = price;
  }

}

public class Test{
  public static void main(String[] args) throws Exception{
    ArrayList<Smartphone> smartphones = new ArrayList<Smartphone>();

    for (int i = 0; i < 5; i++){
      Smartphone s = new Smartphone("12345678" ,"Samsung");
      smartphones.add(s);
    }


    //later I realize I want to add the price, 
    //but it seems the loop I'm using is not working
    for (int i = 0; i < 5; i++){
      smartphones.get(i).setPrice(398);
    }

  }
}

我想知道为什么我使用的循环不起作用,有没有其他方法可以为每部智能手机增加价格?

【问题讨论】:

  • 不工作是什么意思?我的意思是你怎么知道这不起作用。
  • 您的价格设置有效,如果您开始打印价格,您会看到它正在为列表中的每部智能手机打印正确的值
  • 只需在setPrice 行旁边添加System.out.println(smartphones.get(i));,您可能想要覆盖Smartphone.toString() 以获得有用的东西;)
  • 为了让它对初学者更友好,只需将它设为System.out.println(smartphones.get(i).price);
  • 为什么类使用Double包装类?

标签: java loops oop arraylist


【解决方案1】:

您的代码似乎对我有用,但是如果您的意思是它因为看不到价格而无法正常工作,那么您需要做的就是在您的智能手机类中创建一个返回 this.price 的函数并在使用smartphones.get(i).setPrice(398); 后调用它。

【讨论】:

    【解决方案2】:

    在 AIDE 上使用以下代码进行了测试。您的代码工作正常。

    请注意我使用增强的 for 循环来显示价格。如果您不明确需要循环内的索引,则增强的 for 循环是一种遍历列表的干净方法。

    import java.util.ArrayList;
    
    class Smartphone{
        public String serialNo;
        public String brand;
        public Double price;
    
        public Smartphone(String serialNo, String brand){
            this.serialNo = serialNo;
            this.brand = brand;
        }
    
        public void setPrice(double price){
            this.price = price;
        }
    
    }
    
    public class Test{
        public static void main(String[] args) throws Exception{
            ArrayList<Smartphone> smartphones = new ArrayList<Smartphone>();
    
            for (int i = 0; i < 5; i++){
                Smartphone s = new Smartphone("12345678" ,"Samsung");
                smartphones.add(s);
            }
    
    
            //later I realize I want to add the price, 
            //but it seems the loop I'm using is not working
            for (int i = 0; i < 5; i++){
                smartphones.get(i).setPrice(398);
            }
    
            // Display prices to ensure they were set
            for (Smartphone phone : smartphones) {
                System.out.println(phone.price);
    
            }
    
        }
    }
    

    请原谅奇怪的缩进。 AIDE 喜欢使用缩进字符快速而松散地玩游戏。

    【讨论】:

    • 感谢您提供替代循环建议。您的代码运行成功。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-22
    • 2019-06-20
    • 1970-01-01
    相关资源
    最近更新 更多