英文:
Confusion on assigning arrays to object
问题
我有一个文本文件,其中包含各种信息,但归结起来就是姓名/描述/网站,然后按照这个顺序重复,直到文件结束。我应该将文件拿出来,将这三个数据合并成一个对象后对数据进行排序。我对这到底意味着什么以及如何做感到困惑。
这是我教授解释要做的事情的一句话,但我无法理解如何去做。
"您可以设计并实现一个用户定义的对象,其中包括必须将三个属性值组合为单个单元。创建用户定义的对象后,您可以实例化该用户定义的对象的数组。一旦实例化了用户定义的对象的数组,您就可以使用相关的排序算法来对数组中的对象实例进行排序。"
以下是我目前创建的代码。
public class Main {
public static void main(String[] args) {
Junk Stuff = new Junk();
}
public static class Junk {
String[] list = new String[59]; // 存储所有数据的数组
String[] Names = new String[20];
String[] Desc = new String[20];
String[] Websites = new String[20];
int i = 0;
{
File file = new File("Tutorials.txt"); // 打开文件
Scanner sc = null; // 扫描文件
try {
sc = new Scanner(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
sc.hasNextLine(); // 设置循环,当扫描器在文件的下一行时,打印出该行
for (i = 0; i <= list.length; i++) // 循环遍历数组 name = sc.nextLine();
try {
Names[i] = sc.nextLine();
Desc[i] = sc.nextLine();
Websites[i] = sc.nextLine();
} catch (NoSuchElementException e) {
}
}
public String[] getNames() {
return Names.clone();
}
public String[] getDesc() {
return Desc.clone();
}
public String[] getSites() {
return Websites.clone();
}
}
}
英文:
I have a text file with various pieces of information, but it boils down to NAME/DESCRIPTION/WEBSITE and then repeat in that order til the file is done. I am suppose to take the file and sort the data after combining the three datas into a object. I am confused on what that means exactly and how to do it.
This is a quote from my professor explaining what to do but I can't wrap my head around how to do it.
"You can design and implement a user-defined object that consists of the three property values that you must combine as a single unit. Once you create the user-defined object, you can instantiate an array of that user-defined object. Once the instantiate the array of the user-defined object, you can load the array with instances of the associated values. After that, you can use the appropriate sorting algorithms to sort the instances of the objects in the array"
Here is the code I created so far.
public class Main {
public static void main(String[] args) {
Junk Stuff = new Junk();
}
public static class Junk {
String[] list = new String[59]; //array of all the data
String[] Names = new String[20];
String[] Desc = new String[20];
String[] Websites = new String[20];
int i = 0;
{
File file = new File("Tutorials.txt"); //calls file to be opened
Scanner sc = null; // scans file
try {
sc = new Scanner(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
sc.hasNextLine(); //sets while loop that while scanner is on next line of file, prints it
for (i = 0; i <= list.length; i++) //loop to iterate thru array name = sc.nextLine();
try {
Names[i] = sc.nextLine();
Desc[i] = sc.nextLine();
Websites[i] = sc.nextLine();
} catch (NoSuchElementException e) {
}
}
public String[] getNames() {
return Names.clone();
}
public String[] getDesc() {
return Desc.clone();
}
public String[] getSites() {
return Websites.clone();
}
}
}
答案1
得分: 1
我认为你的教授想让你从面向对象编程(OOP)的角度思考,并处理所谓的比较器(用于比较两个对象)。
首先,让我们解释一下对象部分。你正在读取由3个项目组成的数据。你称之为元组(参见这个很好的定义),也称为一组具有共同意义的值。
让我们定义一个对象类来存储这些数据。我们可以称其为Data
,或者也可以是Entity
,甚至是Website
(请注意,我使用了Java的首字母大写约定)。无论如何,要将其与最终运行它的类(你的Main类)分开。
因此,我有以下示例:
package eu.webfarmr;
import java.net.URL;
/**
* Illustrate comparators
* author djob
*
*/
public class Website {
private String name;
private String description;
private URL website;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public URL getWebsite() {
return website;
}
public void setWebsite(URL website) {
this.website = website;
}
}
现在你可以使用另一个类,甚至是这个类中的一个主方法(如果你比较懒),来创建这个对象的数组或列表:
public static void main(String[] args) throws MalformedURLException {
List<Website> websites = new ArrayList<Website>();
Website a = new Website();
a.setName("Let's cook");
a.setDescription("Some fascinating website");
a.setWebsite(new URL("https://www.delscookingtwist.com"));
Website b = new Website();
b.setName("XACML stuff");
b.setDescription("My personal blog");
b.setWebsite(new URL("https://www.webfarmr.eu"));
websites.add(a);
websites.add(b);
}
但是你的教授真正想让你做的是对对象的这个列表或数组进行排序。尽管对数字进行排序很简单(并且内置支持),但对自定义对象进行排序并不简单。什么最重要?标题?描述?URL?如果其中一些值相等怎么办?
这就是比较器的作用。你需要让你的类实现Comparable<T>
。这意味着你的类需要实现以下额外的方法:
@Override
public int compareTo(Website o) {
if (o == null) return 1;
if (this.getName().compareTo(o.getName()) != 0) {
return this.getName().compareTo(o.getName());
} else {
if (this.getWebsite().toString().compareTo(o.getWebsite().toString()) != 0) {
return this.getWebsite().toString().compareTo(o.getWebsite().toString());
} else {
return this.getDescription().compareTo(o.getDescription());
}
}
}
这只是一个示例,你可以更改逻辑。这里是关于compareTo()
的Javadoc:
int eu.webfarmr.Website.compareTo(Website o)
@Override
与指定对象进行比较以确定顺序。返回负整数、零或正整数,如果此对象小于、等于或大于指定的对象。
实现者必须确保 sgn(x.compareTo(y)) == -sgn(y.compareTo(x)) 对于所有的 x 和 y。这意味着如果 y.compareTo(x) 抛出异常,则 x.compareTo(y) 必须抛出异常。
实现者还必须确保关系是传递的:(x.compareTo(y) > 0 && y.compareTo(z) > 0) 意味着 x.compareTo(z) > 0。
最后,实现者必须确保 x.compareTo(y) == 0 意味着对于所有 z,sgn(x.compareTo(z)) == sgn(y.compareTo(z))。
强烈推荐(但不是严格要求)(x.compareTo(y) == 0) == (x.equals(y))。通常情况下,任何实现 Comparable 接口并违反此条件的类都应清楚地指出这一事实。推荐的语言是“注意:这个类具有与 equals 不一致的自然排序。”
请注意,还有许多其他比较方法。请参阅这个网站以获取更多信息。
英文:
I think what your professor is trying to get you to do is to think in terms of OOP (object-oriented programming) and address what's known as comparators (means to compare 2 objects).
First of all, let's address the object part. You are reading data that is made up of 3 items. You call that a Tuple (see this great definition) aka a set of values that have meaning together.
Let's define an object class to store that data. We could call it Data
or maybe Entity
or even Website
(note that I am using Java's first capital letter convention). Whatever you do, keep it away from the class that will eventually run it (your Main).
So as an example I got this:
package eu.webfarmr;
import java.net.URL;
/**
* Illustrate comparators
* @author djob
*
*/
public class Website {
private String name;
private String description;
private URL website;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public URL getWebsite() {
return website;
}
public void setWebsite(URL website) {
this.website = website;
}
}
You can now use another class or maybe even a main method in that class (if you're lazy) to create arrays or lists of that object:
public static void main(String[] args) throws MalformedURLException {
List<Website> websites = new ArrayList<Website>();
Website a = new Website();
a.setName("Let's cook");
a.setDescription("Some fascinating website");
a.setWebsite(new URL("https://www.delscookingtwist.com"));
Website b = new Website();
b.setName("XACML stuff");
b.setDescription("My personal blog");
b.setWebsite(new URL("https://www.webfarmr.eu"));
websites.add(a);
websites.add(b);
}
But what your professor really wants you to do is sort that list or array of objects. While sorting numbers is straightforward (and built-in), it's not straightforward to rank custom objects. What matters most? The title? The description? The URL? What if some of these values are equal?
This is where comparators kick in. You need to get your class to implement Comparable<T>. That means your class needs to implement the following additional method
@Override
public int compareTo(Website o) {
if (o == null) return 1;
// If the names are different then return whichever is the string order
// Consider using lower-case comparison
if (this.getName().compareTo(o.getName())!=0) {
return this.getName().compareTo(o.getName());
} else {
if (this.getWebsite().toString().compareTo(o.getWebsite().toString())!=0) {
return this.getWebsite().toString().compareTo(o.getWebsite().toString());
} else {
return (this.getDescription().compareTo(o.getDescription()));
}
}
}
This is just an example of course, you can change the logic. Here's the Javadoc on compareTo():
> int eu.webfarmr.Website.compareTo(Website o)
>
>
> @Override
>
>
> Compares this object with the specified object for order. Returns
> anegative integer, zero, or a positive integer as this object is
> lessthan, equal to, or greater than the specified object.
>
> The implementor must ensure sgn(x.compareTo(y)) ==-sgn(y.compareTo(x))
> for all x and y. (Thisimplies that x.compareTo(y) must throw an
> exception iff y.compareTo(x) throws an exception.)
>
> The implementor must also ensure that the relation is transitive:
> (x.compareTo(y)>0 && y.compareTo(z)>0) implies x.compareTo(z)>0.
>
> Finally, the implementor must ensure that x.compareTo(y)==0implies
> that sgn(x.compareTo(z)) == sgn(y.compareTo(z)), forall z.
>
> It is strongly recommended, but not strictly required that
> (x.compareTo(y)==0) == (x.equals(y)). Generally speaking, anyclass
> that implements the Comparable interface and violatesthis condition
> should clearly indicate this fact. The recommendedlanguage is "Note:
> this class has a natural ordering that isinconsistent with equals."
>
> In the foregoing description, the notation sgn(expression) designates
> the mathematical signum function, which is defined to return one of
> -1, 0, or 1 according to whether the value of expression is negative, zero or positive.
Note that there are many other ways to compare. See this site for more.
答案2
得分: 0
首先,定义一个名为 'User' 的类,拥有三个字符串属性:name、description 和 website。
接下来,创建一个数据类型为 User 的列表,然后从文件中读取行,创建新的 User 对象并添加到列表中。
然后根据给定的属性对此列表进行排序。
Collections.sort(userList, (u1, u2) -> u1.name.compareTo(u2.name));
英文:
First Define a class 'User' with three string property :name, description and website.
Now create a list with datatype User and then read lines from the file and create new User object and add into list.
Than sort this based on given property.
Collections.sort(userList,(u1,u2)->u1.name.compareTo(u2.name));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论