![](/img/trans.png)
[英]How to use a variable defined inside a method use outside the method in another method on the same Class in java
[英]How to use a variable inside one class/method inside another class?
誰能幫助我,如何將方法中的一個 class 中的變量傳遞給另一個 class,以便我可以繼續使用它? 我的意思是例如下面圖片代碼中的 timeValue。 非常感謝,即使我努力了,我也沒有設法讓它正常工作。
package chattie;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.List;
public class ChatReader {
public List<String> read(File file) {
// public List<String> timeValue;
File path = file;
List<String> timeValue = null;
try (Stream<String> lines = Files.lines(Paths.get(String.valueOf(path)))) {
String content = lines.collect(Collectors.joining(System.lineSeparator()));
String deleter = content.replaceAll("Time:", "").replaceAll("Name:", "").replaceAll("Message:", "");
String line = deleter;
String[] completeArray = line.split("\n");
int l = completeArray.length;
String[] arrayOnlyValues = new String[l];
for (int i = 0; i < completeArray.length; ++i) {
arrayOnlyValues[i] = completeArray[i];
}
List<String> arrayList = new ArrayList<String>(Arrays.asList(completeArray));
arrayList.removeAll(Arrays.asList("", null));
List<String> list1 = arrayList;
int[] t = {0};
timeValue = list1.stream()
.filter(x -> t[0]++ % 3 == 0)
.collect(Collectors.toList());
System.out.println(timeValue);
int[] n = {2};
List<String> list2 = arrayList;
List<String> nameValue = list2.stream()
.filter(x -> n[0]++ % 3 == 0)
.collect(Collectors.toList());
System.out.println(nameValue);
int[] m = {1};
List<String> list3 = arrayList;
List<String> messageValue = list3.stream()
.filter(x -> m[0]++ % 3 == 0)
.collect(Collectors.toList());
System.out.println(messageValue);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
您可以從方法中返回timeValue
:
public List<String> read(File file) {
List<String> timeValue = null;
... // instantiate timeValue
return timeValue;
}
然后從另一個類/方法調用它:
class foo {
public void getTimeValue() {
List<String> timeValue = ChatReader().read(file);
}
}
Hii 將 value 聲明為 class 的成員,而不是 method() 的成員。 你的代碼應該是這樣的:
class aaa {
String value="good luck";
String txt="Best of luck";
void mthod(){
}
}
class bbb {
aaa obj=new aaa();
bbb(){//constructor
System.out.println(obj.value);
}
public static void main(String args[]){
bbb obj2=new bbb();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.