【问题标题】:Can't send string to another class from if loop无法从 if 循环将字符串发送到另一个类
【发布时间】:2012-10-12 15:39:58
【问题描述】:

我正在尝试将字符串从一个类传递到另一个类,但没有成功。我在研究和反复试验期间意识到,我需要有“public static void main(String[] args) {}”才能使用 if 语句,但是 getY() 会产生错误。我可以做些什么不同的事情?

public class Testing {
public static String z;
public static void main(String[] args) {
int x = 15;

if (x >= 10)
    {
    z = "Blabla";
    }
    public static String getZ() {
    return z;
    }
  }
}

另一个类是

class B {
public static void main(String args[]) {
String x = Klasatest2.getZ();

System.out.println(x);
}
}

错误:

Klasatest2.java:14:表达式的非法开始

public static String getZ() 

^

Klasatest2.java:14:表达式的非法开始

public static String getZ() {

       ^

Klasatest2.java:14: ';'预计

public static String getZ() {

                    ^

Klasatest2.java:14: ';'预计

public static String getZ() {

                           ^

4 个错误

【问题讨论】:

    标签: java class inner-classes


    【解决方案1】:

    对于初学者,您不能在方法中声明方法,

    public static void main(String[] args) {
    int x = 15;
    
    if (x >= 10)
        {
        z = "Blabla";
        }
        public static String getZ() {
        return z;
        }
      }
    }
    

    所以你必须确保 get getZ() 方法声明在 main(string[] args) 之外

    这样,

    public class Test {
    public static String z;
    public static void main(String[] args) {
    int x = 15;
    
    if (x >= 10)
        {
        z = "Blabla";
        }
    
      }
    public static String getZ() {
        return z;
        }
    }
    

    另外,你不应该有两个main(String[] args) 方法,因为除非出于某种原因你决定自己调用它,否则只会调用其中一个,这会很奇怪。 因此,如果您希望在 Test 类中设置字符串,则需要从其他类中调用它的 main 方法,可能像这样。

    Test.main(null);
    

    【讨论】:

      【解决方案2】:

      您的应用程序只能有一个main(String args[]) 方法。 试试这个:

      public class Testing {
        public static void main(String[] args) {
          A a = new A("hy");
          B b = new B(a.z);
        }
      
        public class A {
          public String z;
          public A (String z) {
            this.z = z;
          } 
        }
      
        public class B {
          public B (String y) {
            System.out.println(y);
          }
        }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-09-28
        • 1970-01-01
        • 1970-01-01
        • 2011-04-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多