gpt4 book ai didi

Java 将值从数组传递到新对象实例

转载 作者:行者123 更新时间:2023-12-01 17:28:00 25 4
gpt4 key购买 nike

我在将数组值传递给构造函数时遇到一些问题。我有一个 file.txt 其中包含一些带有值的行,例如:

peter|berlin|germany|0930295235|foo.

我弄清楚了如何将行转换为数组。但我不知道如何将数组中的值传递给构造函数,以将数组转换为具有数组属性的对象。

这是主类:

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;


public class FileReader {

public static void main(String[] args) {
try {
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("file.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;

// Read the file line by line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
String s[] = strLine.split("\\|");
// System.out.println(java.util.Arrays.toString(s));
// System.out.println (strLine);
for (String element : s) {
System.out.println(element);
// HERE I NEED TO PASS THE ARRAY VALUES FOR EACH LINE TO TRANSFORM THE ARRAYS TO OBJECTS
Item item = new Item(element,element,element,element,element);
System.out.println("*************************************");
}
// Close the input stream
in.close();
} catch (Exception e) { //Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}

这是类 Item:

public class Item {

private String name;
private String city;
private String state;
private String number;
private String foo;

public Object(String name, String city, String state, String number,String foo){
this.name = name;
this.city = city;
this.state = state;
this.number = number;
this.foo = foo;
}

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getFoo() {
return foo;
}
public void setFoo(String foo) {
this.foo = foo;
}
}

我需要对象来进行更多数据处理。我感谢任何帮助。

最佳答案

我认为您想要做的事情类似于以下内容,尽管并不完全清楚。

String s[] = strLine.split("\\|");
Item item = new Item(s[0], s[1], s[2], s[3], s[4]);

另请注意,在创建新的 Item 对象后,它几乎会立即超出范围,因此您需要将其存储在 while 之外声明的某种容器中 循环:

List<Item> items = new ArrayList<Item>();
String line;

while((line = br.readLine()) != null) {
String[] words = line.split("\\|");
Item item = new Item(words[0], words[1], words[2], words[3], words[4]);
items.add(item);
}

关于Java 将值从数组传递到新对象实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13528532/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com