Java 如何获取字符串以获取方法中的整数

Java 如何获取字符串以获取方法中的整数,java,string,integer,Java,String,Integer,我为下面的问题创建了一个示例类 public class testClass { public void testMethod() { int testInteger = 5; } String testString = "Hello World" + testInteger; } 我在一个方法中有一个整数,在上面的方法中没有一个字符串。我希望字符串获得方法中的整数,但它不能。有人能解释一下为什么会这样,并告诉我如何使字

我为下面的问题创建了一个示例类

    public class testClass {

     public void testMethod()
     {
         int testInteger = 5;
     }

     String testString = "Hello World" +  testInteger;

}

我在一个方法中有一个整数,在上面的方法中没有一个字符串。我希望字符串获得方法中的整数,但它不能。有人能解释一下为什么会这样,并告诉我如何使字符串成为整数吗。谢谢

让我们把代码分解一下,看看是怎么回事

你有这样一个功能

 public void testMethod()
 {
     int testInteger = 5;
 }
正如您所看到的,返回类型为void,因此不会返回任何被称为此方法的地方

在testMethod之后有这一行

String testString = "Hello World" + testInteger;
首先看起来很奇怪为什么

因为您没有任何main方法,所以我不知道您的代码如何运行

但假设你有这样的主要方法

public static void main(String[] args){
     String testString = "Hello World" + testInteger;
 }
其次,您甚至没有调用testMethod以便在主方法中使用它 问题

一,。您根本没有调用testMethod

二,。即使您调用了它,它也不会帮助您,因为您的返回类型是void

三,。您需要main方法才能运行代码

补救措施

一,。将返回类型更改为int

您的函数签名:

public int testMethod()    
二,。如果你想使用你的方法,你必须在你的主要方法中使用它,比如

例如:

String testString = "Hello World" + testMethod();
public class testClass {

     public int testMethod()
     {
         int testInteger = 5;
         return testInteger;
     }

    String testString = "Hello World" + testMethod();

}
三,。不要忘记使用main方法,因为它是运行代码所必需的

您的主要方法签名是

 public static void main(String[] args)
例如:

String testString = "Hello World" + testMethod();
public class testClass {

     public int testMethod()
     {
         int testInteger = 5;
         return testInteger;
     }

    String testString = "Hello World" + testMethod();

}

整数是方法内部的一个变量;它具有方法的作用域,这意味着不能从方法外部访问它。字符串是一个字段;它具有类的作用域,因此可以从类中的任何位置(包括方法内部)访问它。

它是基本的Java。。。testInteger在方法中定义,因此在方法外不可用。您可以让该方法返回一个int作为您的testinger并调用该方法。

如果不返回局部变量,则无法从另一个方法访问该局部变量

public int testMethod()
{
  int testInteger = 5;
  return testInteger;
}
然后,如果在引用实例中有类的实例,则可以通过调用该方法来获取该值

局部变量与对象在字段中存储其状态的方式类似,方法通常将其临时状态存储在局部变量中。声明局部变量的语法类似于声明字段,例如int count=0;。没有将变量指定为局部变量的特殊关键字;这个决定完全来自于变量被声明的位置——在一个方法的开始括号和结束括号之间。因此,局部变量只对声明它们的方法可见;他们不能从班上的其他人那里得到


这并不能回答提问者的问题。@1337比k你看起来更好吗?你不能这样做,因为这没有任何意义。你能解释一下你预期会发生什么吗?在调用方法之前和之后,testString应该是什么?是的,必须从方法返回整数或使用成员变量。不过,这个问题很有趣