gpt4 book ai didi

java - 如何在Java中调用类

转载 作者:行者123 更新时间:2023-12-01 06:21:19 25 4
gpt4 key购买 nike

有两个字符串,String1 = hello String2 = world,我想调用一个Hello类并发送到这两个字符串。该类应返回一个 boolean 值和一个字符串。如果 boolean 值为 true,则应执行以下操作:

 System.out.println("Hello to you too!");

有人可以帮我解决这个代码吗?

最佳答案

首先,一个术语问题:你不能“调用一个类”。您可以调用类上的方法,例如:

someObject.someMethod(string1, string2);

更重要的是,您不能从一个方法返回两个不同的值。不过,您当然可以在对象中存储两个不同的值并从不同的方法返回它们。也许是这样的类:

public class Foo {
protected boolean booleanThing;
protected String stringThing;

public void yourMethod(String string1, String string2) {
// Do processing
this.booleanThing = true;
this.stringThing = "Bar";
}
public String getString() {
return this.stringThing;
}
public boolean getBoolean() {
return this.booleanThing;
}
}

将用作:

someObject.yourMethod(string1, string2);
boolean b = someObject.getBoolean();
String s = someObject.getString();

尽管如此,这可能根本不是解决您实际问题的最佳方法。也许你可以更好地解释你想要完成的任务。也许抛出Exception比尝试返回 boolean 值更好,或者也许完全有另一种解决方案。

我们掌握的细节越多越好。

关于java - 如何在Java中调用类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4018236/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com