使用一个对象数组或ArrayList,以便将文件中的所有记录都存储在内存中。

huangapple go评论86阅读模式
英文:

use an array or arrayList ofan objects so that all of its records from the file can be stored in memory

问题

我是Java初学者,对我的练习感到困扰。

这是我的Client.txt文件:

1,Jay,Walker,91 Boland Drive,BAGOTVILLE,NSW,2477
2,Mel,Lowe,45 Ocean Drive,MILLERS POINT,NSW,2000
3,Hugh,Manatee,32 Edgecliff Road,REDFERN,NSW,2016
4,Elizabeth,Turner,93 Webb Road,MOUNT HUTTON,NSW,2290

这是我的Client类(带有构造函数):

public class Client {
    private int clientID;
    private String firstName;
    private String surName;
    private String street;
    private String suburb;
    private String state;
    private int postcode;

    // 构造函数
    public Client(int ID, String fName, String sName, String str, String sb, String sta, int pCode) {
        clientID = ID;
        firstName = fName;
        surName = sName;
        street = str;
        suburb = sb;
        state = sta;
        postcode = pCode;
    }
}

这是我的代码,用于创建对象并读取从txt文件中读取的记录:

File inFile = new File("clients.txt");
Scanner inputFile = new Scanner(inFile);
String str;
String[] tokens;
while (inputFile.hasNext()) {
    str = inputFile.nextLine();         // 从文件中读取一行文本
    tokens = str.split(",");            // 使用逗号作为分隔符拆分行

    // 将已打印的每个标记映射到Client类中的相应字段
    // 因为tokens[0]的类型是String,但clientID的类型是int,
    // 我们需要解析它并获取整数表示。
    // 我们对postcode也采取同样的做法
    int clientID = Integer.parseInt(tokens[0]);
    String firstName = tokens[1];
    String surName = tokens[2];
    String street = tokens[3];
    String suburb = tokens[4];
    String state = tokens[5];
    int postcode = Integer.parseInt(tokens[6]);

    // 创建一个新的`Client`类型的对象
    // 并传递所有收集到的信息。
    Client client = new Client(clientID, firstName, surName, street, suburb, state, postcode);
    System.out.println(client + "\n");

} // 结束while循环

练习的要求是现在我必须修改程序,以利用一个数组或ArrayList来存储这个Client对象,以便从文件中读取的所有Client记录可以轻松地存储在内存中,并且从文件中创建的每个对象都被放入Client对象的数组/ArrayList中。

我刚刚开始学习数组和ArrayList,所以对于如何完成这些练习我一无所知。有人可以帮助我吗?

英文:

I'm a Java beginner and I'm having trouble with my exercises.

This is my Client.txt file:
<!-- language: lang-none -->
1,Jay, Walker,91 Boland Drive,BAGOTVILLE,NSW,2477
2,Mel, Lowe,45 Ocean Drive,MILLERS POINT,NSW,2000
3,Hugh, Manatee,32 Edgecliff Road,REDFERN,NSW,2016
4,Elizabeth, Turner,93 Webb Road,MOUNT HUTTON,NSW,2290

This is my Client class (have constructor):

public class Client {
	private int clientID;
	private String firstName;
	private String surName;
	private String street;
	private String suburb;
	private String state;
	private int postcode;
	
	// constructor
	public Client (int ID, String fName, String sName, String str, String sb, String sta, int pCode) {
		
		clientID = ID;
		firstName = fName;
		surName = sName;
		street = str;
		suburb = sb;
		state = sta;
		postcode = pCode;
	}

This is my code creating object and read the records that are read from the txt file:

File inFile = new File(&quot;clients.txt&quot;);
Scanner inputFile = new Scanner(inFile);
String str;
String[] tokens;
while (inputFile.hasNext()) {
	
	str = inputFile.nextLine();         // read a line of text from the file 
	tokens = str.split(&quot;,&quot;);            // split the line using commas as delimiter
	
	// map each token that is already printed to corresponding field in Client class
	// Because tokens[0] is of type String but clientID is of type int,
	// we need to parse it and get the integer representation.
	// we also do the same thing with postcode 
	int clientID = Integer.parseInt(tokens[0]);
	String firstName = tokens[1];
	String surName = tokens[2];
	String street = tokens[3];
	String suburb = tokens[4];
	String state = tokens[5];
	int postcode = Integer.parseInt(tokens[6]);	
	
	// create a new object of `Client` type
	// and pass all the gathered information.
	Client client = new Client(clientID, firstName, surName, street, suburb, state, postcode);
    System.out.println(client + &quot;\n&quot;);
		
} // end while

The requirement of the exercise is now I have to modify the program to utilise an array or arrayList of this Client object, so that all of the Client records from the file can be easily stored in memory, and each objects is created from the file place it into the array/arrayList of client objects

I have just begin to study array and arrayList few week, so I have no idea of doing this exercises. Can anyone help me?

答案1

得分: 0

在你的 while 循环之前创建一个 ArrayList

ArrayList<Client> cList = new ArrayList<>();

在你的循环中,

Client client = new Client(clientID, firstName, surName, street, suburb, state, postcode);

// 添加到列表
cList.add(client);
英文:

Before your while loop create a ArrayList

ArrayList&lt;Client&gt; cList = new ArrayList&lt;&gt; ();

In your loop,

Client client = new Client(clientID, firstName, surName, street, suburb, state, postcode);

// add to list
cList.add (client);

答案2

得分: 0

在 while 循环上方,您可以简单地创建一个新列表:

List<Client> clientList = new ArrayList<>();

然后在每次创建 new Client(..) 之后将其添加到客户列表中:

clientList.add(client);
英文:

Above the while loop you can simply create a new list

List&lt;Client&gt; clientList = new ArrayList&lt;&gt;();

and then add to the client list after you make each new Client(..)

with clientList.add(client)

答案3

得分: 0

你可以重写Client的构造函数,这样它也可以接受来自文件的一行内容:

import java.util.stream.Stream;

public class Client {
    // ...(其他属性和构造函数)

    public Client(String line) {
        String[] split = line.split(",");
        this.clientId = Integer.parseInt(split[0]);
        this.firstName = split[1];
        this.lastName = split[2].trim();
        this.street = split[3];
        this.suburb = titleCase(split[4]);
        this.state = split[5];
        this.postcode = Integer.parseInt(split[6]);
    }

    // ...(其他方法)

    private String titleCase(String suburb) {
        return Stream.of(suburb.split(" ")).map(w -> w.toUpperCase().charAt(0) + w.toLowerCase().substring(1))
            .reduce((s, s2) -> s + " " + s2).orElse("");
    }
}

同时,在处理Scanner时也可以使用try-with-resources

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        List<Client> clientList = new ArrayList<>();

        try (Scanner scanner = new Scanner(new File("Clients.txt"))) {
            while (scanner.hasNext()) {
                String line = scanner.nextLine();
                clientList.add(new Client(line));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        for (Client client : clientList) {
            System.out.println(client);
        }
    }
}

输出:

Jay Walker - 91 Boland Drive, Bagotville - NSW, 2477
Mel Lowe - 45 Ocean Drive, Millers Point - NSW, 2000
Hugh Manatee - 32 Edgecliff Road, Redfern - NSW, 2016
Elizabeth Turner - 93 Webb Road, Mount Hutton - NSW, 2290

此处可以尝试运行代码。

英文:

You could override the constructor of Client so that it could also just take in a line from the file:

import java.util.stream.Stream;

public class Client {
    private int clientId;
    private String firstName;
    private String lastName;
    private String street;
    private String suburb;
    private String state;
    private int postcode;

    public Client(int clientId, String firstName, String lastName, String street, String suburb, String state,
            int postcode) {
        this.clientId = clientId;
        this.firstName = firstName;
        this.lastName = lastName;
        this.street = street;
        this.suburb = suburb;
        this.state = state;
        this.postcode = postcode;
    }

    public Client(String line) {
        String[] split = line.split(&quot;,&quot;);
        this.clientId = Integer.parseInt(split[0]);
        this.firstName = split[1];
        this.lastName = split[2].trim();
        this.street = split[3];
        this.suburb = titleCase(split[4]);
        this.state = split[5];
        this.postcode = Integer.parseInt(split[6]);
    }

    @Override
    public String toString() {
        return String.format(&quot;%s %s - %s, %s - %s, %d&quot;, this.firstName, this.lastName, this.street, this.suburb,
                this.state, this.postcode);
    }

    private String titleCase(String suburb) {
        return Stream.of(suburb.split(&quot; &quot;)).map(w -&gt; w.toUpperCase().charAt(0) + w.toLowerCase().substring(1))
                .reduce((s, s2) -&gt; s + &quot; &quot; + s2).orElse(&quot;&quot;);
    }
}

And also use try-with-resources for your Scanner:

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        List&lt;Client&gt; clientList = new ArrayList&lt;&gt;();

        try (Scanner scanner = new Scanner(new File(&quot;Clients.txt&quot;))) {
            while (scanner.hasNext()) {
                String line = scanner.nextLine();
                clientList.add(new Client(line));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        for (Client client : clientList) {
            System.out.println(client);
        }
    }
}

Output:

Jay Walker - 91 Boland Drive, Bagotville - NSW, 2477
Mel Lowe - 45 Ocean Drive, Millers Point - NSW, 2000
Hugh Manatee - 32 Edgecliff Road, Redfern - NSW, 2016
Elizabeth Turner - 93 Webb Road, Mount Hutton - NSW, 2290

Try it out here.

huangapple
  • 本文由 发表于 2020年10月23日 10:56:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/64493208.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定