[英]How to use a variable inside one class/method inside another class?
could anyone help me, how to pass a variable inside one class inside a method to another class, so that I can continue to work with it?谁能帮助我,如何将方法中的一个 class 中的变量传递给另一个 class,以便我可以继续使用它? I mean for example timeValue from the code below on pictures.
我的意思是例如下面图片代码中的 timeValue。 Thanks a lot, I did not manage to to get it to work correctly, even i tried hard.
非常感谢,即使我努力了,我也没有设法让它正常工作。
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;
}
}
You could just return timeValue
from the method:您可以从方法中返回
timeValue
:
public List<String> read(File file) {
List<String> timeValue = null;
... // instantiate timeValue
return timeValue;
}
Then call it from another class/method:然后从另一个类/方法调用它:
class foo {
public void getTimeValue() {
List<String> timeValue = ChatReader().read(file);
}
}
Hii declare value as a member of class not as the member of method(). Hii 将 value 声明为 class 的成员,而不是 method() 的成员。 Your code should be like this:
你的代码应该是这样的:
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.