有两个字符串,String1 = hello String2 = world,我想调用一个类Hello并发送到这两个字符串。该类应该返回一个布尔值和一个字符串。如果布尔值为true,则应执行以下操作:
System.out.println("Hello to you too!");有人能帮我解决这段代码吗?
发布于 2010-10-26 03:51:30
首先,有一个术语问题:您不能“调用类”。您可以在类上调用方法,例如:
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比尝试返回一个布尔值更好,或者可能有完全不同的解决方案。
我们掌握的细节越多越好。
发布于 2010-10-26 03:52:13
你应该检查你的类的定义,但现在我假设这就是你的意思,如果这不是你想要的,请评论:
public class Hello {
private final String first;
private final String second;
public static void main(String[] args) {
String s1 = "Hello";
String s2 = "World";
Hello h = new Hello(s1,s2);
if(h.isHelloWorld()) {
System.out.println("Hello to you too!");
}
}
private Hello(String first, String second) {
this.first = first;
this.second = second;
}
private boolean isHelloWorld() {
return (first.equals("Hello") && second.equals("World"));
//If that scares you then do this instead:
/**
if(first.equals("Hello") && second.equals("World") {
return true;
} else { return false; }
**/
}
}当你运行这个程序时,它将总是打印“你也好!”,如果你更改了s1或s2,它将不会打印任何东西。
发布于 2010-10-26 03:52:28
public class Hello{
boolean val = false;
String str = "";
public Hello(String a, String b){
if(a == "hello" && b == "world"){
this.val = true;
this.str = "hello to you too";
}
}
public static void main(String args[]){
String a = "hello";
String b = "world";
Hello hello = new Hello(a,b);
if(hello.val == true)
System.out.println(hello.str);
}
}https://stackoverflow.com/questions/4018236
复制相似问题