2010-10-25 32 views
1

有两个字符串,String1 = hello String2 = world,我想调用一个类Hello并发送给两个字符串。该类应该返回一个布尔值和一个字符串。如果布尔值为true,则应该遵循以下规则:如何在Java中调用一个类

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

有人可以帮我解决这个问题吗?

+0

返回一个布尔值和一个字符串,你将不得不创建一个对象。 – Orbit 2010-10-25 19:45:54

+0

我该怎么做? – Hammer 2010-10-25 19:48:41

+0

目前您阅读过多少个教程/书籍? – Bozho 2010-10-25 19:50:20

回答

1

首先,一个术语问题:你不能“叫一个类”。您可以拨打一个方法的一类,如:

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比试图返回一个布尔值更好,或者也许完全是另一个解决方案。

我们的细节越多越好。

0

建议您检查类的定义,但现在我会认为这是你的意思,评论,如果这不是你想找的:

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它不会打印任何东西。

-2
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); 
} 
} 
+0

你是否在MS Word或类似的类型?为什么首都'公共'和'类'? :) – 2010-10-25 19:56:25

+1

呃...责备那个布朗尼。 – Orbit 2010-10-25 20:02:33

+0

函数不是Java中的关键字...(-1) – 2010-10-25 20:05:02

相关问题