【问题标题】:Java OOP: check if X or Y object is in Array[i], then print textJava OOP:检查 X 或 Y 对象是否在 Array[i] 中,然后打印文本
【发布时间】:2021-05-12 03:41:58
【问题描述】:

我试图弄清楚如何使用声明的方法处理数组索引以进行快速列表编辑,我想到了这个自我示例:

假设我有一个包含 x 和 yn 对象的数组列表,我想创建两个方法,在数组的特定索引中搜索所需的对象并更改它并打印适当的行,例如:

class Testing
public static void main(String[] args){
//The objects were created from a constructor from an other X class 
Object [] objectsList1 = {x,x,y1,x};
Object [] objectsList2 = {y2, y3, x, x};


//check if x exists in [k]objectsList1, if it does print 1, if it doesn't change it to desired yn and print2.
//check if not-x exists in [k]objectsList1, if it does print 3, if it doesn't change it to x and print4.
}

我的想法是我需要 2 个布尔方法来检查 x 或 y 是否存在,使用 if 和 else 语句,然后在 changeX 和 changeY 方法中使用这些方法,但我正在努力如何声明4个方法,因为索引而实现它。

Class ChangeNCheck;
//x is declared here and is static (could need to move yn objects here and declare them static?)
//define methods for this
public Boolean checkX(){}
public Boolean checkY(){}
changeX(){}
changeY(){}

请在 main 中显示 4 种情况的示例,并在 changeNCheck 类中声明适当的方法。

编辑: 以下 if 语句适用于 x 和 objectsList1:

if (x.equals(objectsList1[i]))
                System.out.println("4");
        else {
                objectsList1[i] = x;
                System.out.println("3");
        }
//same for yn

但是,我不能让自己声明一个方法来执行所有这些操作,以避免在任何地方重复编写它。

编辑 2:对数组 objectsListn 使用适当的约定。

【问题讨论】:

  • X和Y类的实现是什么?
  • 我想用它们来打印,我有几种方法来处理 [i] 索引是否包含 x (如果为真则更改特定变量),并使用构造函数声明它们(int z,字符串代码)。
  • 无关:在命名变量时请多加小心。首先ArrayList 是java.util 集合框架中的一个类。将数组命名为“ArrayListx”会让您的读者超级感到困惑。并且:变量名在 java 中采用 camelCase。他们从不开始大写!
  • @GhostCat 谢谢!我修好了它们。我真的很感谢所有关于约定的技巧,因为除了在这个启示录中简短地教过我们之外,我们没有被教过。
  • 这不是答案,但我仍然在问这是否是您想要的? checkAndChange(String element, String[] array, int index){ if (element.equals(array[index])) System.out.println("你的消息");否则 { 数组 [索引] = 元素; System.out.println("你的留言"); } }

标签: java arrays oop indexing


【解决方案1】:

这可能会有所帮助...

public void checkAndChange(String element, String[] array, int index) {
            if (element.equals(array[index])) {
                System.out.println("your message");
            } else {
                array[index] = element;
                System.out.println("your Message");
            }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多