Java方法使用ListIterator返回列表中的所有元素

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

Java method with Listiterator to return all elements in a list

问题

import java.util.*;

public class TrainingRecord {
    private List<Entry> tr;

    public TrainingRecord() {
        tr = new ArrayList<Entry>();
    } // constructor

    public void addEntry(Entry e) {
        tr.add(e);
    }

    public String lookupEntry(int d, int m, int y) {
        ListIterator<Entry> iter = tr.listIterator();
        String result = "No entries found";
        while (iter.hasNext()) {
            Entry current = iter.next();
            if (current.getDay() == d && current.getMonth() == m && current.getYear() == y)
                result = current.getEntry();
        }
        return result;
    }

    public String findAllEntries(int d, int m, int y) {
        String result = "No entries found";
        List<String> matchingEntries = new ArrayList<>();
        
        for (Entry current : tr) {
            if (current.getDay() == d && current.getMonth() == m && current.getYear() == y) {
                matchingEntries.add(current.getEntry());
            }
        }
        
        if (!matchingEntries.isEmpty()) {
            result = String.join("\n", matchingEntries);
        }
        
        return result;
    }
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class TrainingRecordGUI extends JFrame implements ActionListener {
    // ... (other GUI components and constructor)

    public void actionPerformed(ActionEvent event) {
        if (event.getSource() == addR) {
            // ... (add entry logic)
        }
        if (event.getSource() == lookupR) {
            // ... (lookup entry logic)
        }
        if (event.getSource() == findAllByDate) {
            int m = Integer.parseInt(month.getText());
            int d = Integer.parseInt(day.getText());
            int y = Integer.parseInt(year.getText());
            outputArea.setText("looking up record ...");
            String result = myAthletes.findAllEntries(d, m, y);
            outputArea.setText(result);
        }

        blankDisplay();
    }

    public static void main(String[] args) {
        TrainingRecordGUI applic = new TrainingRecordGUI();
    }
}

Please note that I've only included the translated and corrected parts of your code. The unchanged parts of the code should remain as they are. Make sure to integrate these changes into your existing code structure.

英文:

I am pretty new to this , so there it goes.

I have a Training record GUI that keeps track of athletes performances.
I am struggling to write the method findAllEntries. It is supposed to go through the list and return all elements that match certain date, month and year as a String( Similar to lookupEntry, but I need all elements displayed in one string??)

For example when I run the code it should show Bob and Alice entries, but it only shows Bobs.

No matter what I do it gives me only one element.

All help will be appreciated!

// An implementation of a Training Record as an ArrayList
import java.util.*;
public class TrainingRecord {
private List&lt;Entry&gt; tr;
public TrainingRecord() {
tr = new ArrayList&lt;Entry&gt;();
} // constructor
// add a record to the list
public void addEntry(Entry e) {
tr.add(e);
} // addClass
// look up the entry of a given day and month
public String lookupEntry(int d, int m, int y) {
ListIterator&lt;Entry&gt; iter = tr.listIterator();
String result = &quot;No entries found&quot;;
while (iter.hasNext()) {
Entry current = iter.next();
if (current.getDay() == d &amp;&amp; current.getMonth() == m &amp;&amp; current.getYear() == y)
result = current.getEntry();
}
return result;
} // lookupEntry
public String findAllEntries(int d, int m, int y) {
// I am stuck here
String result = &quot;No entries found&quot;;
return result;
} // findAllEntries
}
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import java.lang.Number;
public class TrainingRecordGUI extends JFrame implements ActionListener {
private JTextField name = new JTextField(30);
private JTextField day = new JTextField(2);
private JTextField month = new JTextField(2);
private JTextField year = new JTextField(4);
private JTextField hours = new JTextField(2);
private JTextField mins = new JTextField(2);
private JTextField secs = new JTextField(2);
private JTextField dist = new JTextField(4);
private JLabel labn = new JLabel(&quot; Name:&quot;);
private JLabel labd = new JLabel(&quot; Day:&quot;);
private JLabel labm = new JLabel(&quot; Month:&quot;);
private JLabel laby = new JLabel(&quot; Year:&quot;);
private JLabel labh = new JLabel(&quot; Hours:&quot;);
private JLabel labmm = new JLabel(&quot; Mins:&quot;);
private JLabel labs = new JLabel(&quot; Secs:&quot;);
private JLabel labdist = new JLabel(&quot; Distance (km):&quot;);
private JButton addR = new JButton(&quot;Add&quot;);
private JButton lookupR = new JButton(&quot;Look Up&quot;);
private JButton findAllByDate = new JButton(&quot;Find All&quot;);
private TrainingRecord myAthletes = new TrainingRecord();
private JTextArea outputArea = new JTextArea(5, 50);
public static void main(String[] args) {
TrainingRecordGUI applic = new TrainingRecordGUI();
} // main
// set up the GUI
public TrainingRecordGUI() {
super(&quot;Training Record&quot;);
setLayout(new FlowLayout());
add(labn);
add(name);
name.setEditable(true);
add(labd);
add(day);
day.setEditable(true);
add(labm);
add(month);
month.setEditable(true);
add(laby);
add(year);
year.setEditable(true);
add(labh);
add(hours);
hours.setEditable(true);
add(labmm);
add(mins);
mins.setEditable(true);
add(labs);
add(secs);
secs.setEditable(true);
add(labdist);
add(dist);
dist.setEditable(true);
add(addR);
addR.addActionListener(this);
add(lookupR);
lookupR.addActionListener(this);
add(outputArea);
add(findAllByDate);
findAllByDate.addActionListener(this);
add(outputArea);
outputArea.setEditable(false);
setSize(720, 200);
setVisible(true);
blankDisplay();
// test cases)
Entry a = new Entry(&quot;Alice&quot;, 1, 2, 2003, 0, 16, 7, 3);
Entry b = new Entry(&quot;Bob&quot;, 1, 2, 2003, 0, 14, 15, 3);
Entry c1 = new Entry(&quot;Claire&quot;, 7, 3, 2010, 0, 26, 20, 7);
Entry c2 = new Entry(&quot;Claire&quot;, 11, 3, 2010, 0, 24, 55, 7);
myAthletes.addEntry(a);
myAthletes.addEntry(b);
myAthletes.addEntry(c1);
myAthletes.addEntry(c2);
} // constructor
// listen for and respond to GUI events
public void actionPerformed(ActionEvent event) {
if (event.getSource() == addR) {
String n = name.getText();
int m = Integer.parseInt(month.getText());
int d = Integer.parseInt(day.getText());
int y = Integer.parseInt(year.getText());
float km = java.lang.Float.parseFloat(dist.getText());
int h = Integer.parseInt(hours.getText());
int mm = Integer.parseInt(mins.getText());
int s = Integer.parseInt(secs.getText());
Entry e = new Entry(n, d, m, y, h, mm, s, km);
myAthletes.addEntry(e);
outputArea.setText(&quot;Record added\n&quot;);
}
if (event.getSource() == lookupR) {
int m = Integer.parseInt(month.getText());
int d = Integer.parseInt(day.getText());
int y = Integer.parseInt(year.getText());
outputArea.setText(&quot;looking up record ...&quot;);
String result = myAthletes.lookupEntry(d, m, y);
outputArea.setText(result);
}
if (event.getSource() == findAllByDate) {
int m = Integer.parseInt(month.getText());
int d = Integer.parseInt(day.getText());
int y = Integer.parseInt(year.getText());
outputArea.setText(&quot;looking up record ...&quot;);
String result = myAthletes.findAllEntries(d, m, y);
outputArea.setText(result);
}
blankDisplay();
} // actionPerformed
public void blankDisplay() {
name.setText(&quot;&quot;);
day.setText(&quot;&quot;);
month.setText(&quot;&quot;);
year.setText(&quot;&quot;);
hours.setText(&quot;&quot;);
mins.setText(&quot;&quot;);
secs.setText(&quot;&quot;);
dist.setText(&quot;&quot;);
}

答案1

得分: 1

public String lookupEntry(int d, int m, int y) {
    ListIterator<Entry> iter = tr.listIterator();
    StringBuilder result = new StringBuilder(""); //1
    while (iter.hasNext()) {
        Entry current = iter.next();
        if (current.getDay() == d && current.getMonth() == m && current.getYear() == y)
            result.append(current.getEntry() + " ");
    }
    //2
    if (result.equals("")) {
        result.append("No entries found");
    }
    return result.toString();
} // lookupEntry
  1. 我们使用StringBuilder而不是字符串,以便它占用更少的空间,并且每次找到新条目时我们都在追加字符串。

  2. 如果字符串为空,则将显示为“未找到结果”。

英文:
public String lookupEntry(int d, int m, int y) {
ListIterator&lt;Entry&gt; iter = tr.listIterator();
StringBuilder result=new StringBuilder(&quot;&quot;); //1
while (iter.hasNext()) {
Entry current = iter.next();
if (current.getDay() == d &amp;&amp; current.getMonth() == m &amp;&amp; current.getYear() == y)
result.append(current.getEntry()+&quot; &quot;);
}
//2
if(result.equals(&quot;&quot;)){
result.append(&quot;No entires found&quot;);
}
return result.toString();
} // lookupEntry
  1. We are using StringBuilder instead of a string so that it will take less space and we are appending string every time when we find the new entry.

  2. If string will be empty then it will be "no result found".

答案2

得分: 0

我不确定如果有多个条目时您希望字符串包含什么内容,但实质上您需要在lookupEntry中已有的while循环中重复执行。您可以通过将测试代码隔离到一个私有方法中来清理代码,但仅限于此。

此外,在大多数可用的Java版本中,您可以使用扩展的for语法来迭代Collection类型,例如:

for (Entry current: tr) {
    if (current.getDay() == d && current.getMonth() == m && current.getYear() == y)
        ...
}
英文:

I'm not sure what you expect the string to contain if there are multiple entries, but you essentially need to repeat the while loop that you already have in lookupEntry. You can clean up the code by isolating the test code in a private method, but that's about it.

Also, in most available versions of Java, you can use the expanded for syntax to iterate a Collection type, e.g.:

for (Entry current: tr) {
if (current.getDay() == d &amp;&amp; current.getMonth() == m &amp;&amp; current.getYear() == y)
...
}

huangapple
  • 本文由 发表于 2020年4月7日 22:48:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/61082792.html
匿名

发表评论

匿名网友

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

确定