首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在Java中调用类

如何在Java中调用类
EN

Stack Overflow用户
提问于 2010-10-26 03:44:37
回答 3查看 26.1K关注 0票数 1

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

代码语言:javascript
运行
复制
 System.out.println("Hello to you too!");

有人能帮我解决这段代码吗?

EN

回答 3

Stack Overflow用户

发布于 2010-10-26 03:51:30

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

代码语言:javascript
运行
复制
someObject.someMethod(string1, string2);

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

代码语言:javascript
运行
复制
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;
    }
}

它将被用作:

代码语言:javascript
运行
复制
someObject.yourMethod(string1, string2);
boolean b = someObject.getBoolean();
String s = someObject.getString();

话虽如此,但这可能根本不是解决实际问题的最佳方法。也许你可以更好地解释你想要实现的目标。也许抛出一个Exception比尝试返回一个布尔值更好,或者可能有完全不同的解决方案。

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

票数 1
EN

Stack Overflow用户

发布于 2010-10-26 03:52:13

你应该检查你的类的定义,但现在我假设这就是你的意思,如果这不是你想要的,请评论:

代码语言:javascript
运行
复制
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,它将不会打印任何东西。

票数 0
EN

Stack Overflow用户

发布于 2010-10-26 03:52:28

代码语言:javascript
运行
复制
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);
 }
}
票数 -2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4018236

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档