How to print objects from an Array to a TextField - java

Problem: I am unable to return values entered in an Array to a preview textbox
Ideal solution: User presses refresh, the box is populated with the objects in the array.
JDK: 1.8
Working Command Line Version Code:
public static void printAll(Member[] platoon){
//System.out.println("You are in the third loop");
for (int cntr=0;cntr<platoon.length;cntr++){
System.out.println("Member Name: " + platoon[cntr].getName() + " " + "Join Date: " + platoon[cntr].getJoinDate());
}
}
The above code takes a instantiated array of object type Members and returns via get methods each value stored in each Member(String Name, int day, int month, int year);.
I am attempting to do the same thing with the GUI abilities of Java. My code is somewhere around 300 lines, I am definitely willing to post it all as this is the last thing keeping me from finishing my project.
Below I write the action event that I want to use to set the text in the preview textfield with the current contents of the platoon Array. All I was attempting to do with this was place the print out from the above code into the box, it does not like the type VOID so i switched it to the return type String. Now It doesn't appear I can store the results of a For loop as a String? I am surley missing something vital.
GUI Code:
}else if(event.getSource() == refreshButton){
displayText.setText(setPreview(platoon));
}
public static String setPreview(Member[] platoon){
//System.out.println("You are in the fourth loop");
preview = (for (int cntr=0;cntr<platoon.length;cntr++){
System.out.println("Member Name: " + platoon[cntr].getName() + " " + "Join Date: " + platoon[cntr].getJoinDate()););
return preview;
}
}
Thank you all for your help, will keep this OP updated to help future Stack Overflow members with this issue.

Loops don't return results, interesting idea, Java just doesn't do.
You could...
Use a StringJoiner
StringJoiner joiner = new StringJoiner("\n");
for (int cntr=0;cntr<platoon.length;cntr++){
joiner.add("Member Name: " + platoon[cntr].getName() + " " + "Join Date: " + platoon[cntr].getJoinDate());
}
return joiner.toString();
You could...
Use JTextArea#append
for (int cntr = 0; cntr < platoon.length; cntr++) {
ta.append("Member Name: " + platoon[cntr].getName() + " " + "Join Date: " + platoon[cntr].getJoinDate() + "\n");
}
You could...
Use JList which is designed to present a list of "stuff".
See How to use lists for more details

Your problem is in your setPreview method. You using System.out.println which is an instruction to print text to the system's standard output device (in most cases a terminal window). It does not return a string, and you cannot concatenate a string to a variable using this syntax:
preview = for(...) { ... }
Since setPreview will return a single String I suspect you want to do this instead:
public static String setPreview(Member[] platoon){
String result = "";
for (int cntr=0;cntr<platoon.length;cntr++){
if (result.length() > 0) result += " "; // put a space before the next output
result += "Member Name: " + platoon[cntr].getName() + " " + "Join Date: " + platoon[cntr].getJoinDate());
}
return result;
}
This will build up the output string you need which can then be set to the text field or whatever is appropriate.

Override the toString() method in Member:
#Override
public String toString() {
return "Member Name: " + getName() + " Join Date: " + getJoinDate();
}
PrintAll() will become (but you don't need it any more):
public static void printAll(Member[] platoon) {
for (int cntr = 0; cntr < platoon.length; cntr++)
System.out.println(platoon[cntr].toString());
}
setPreview() will become (NOTE: this is only to show the principle, for better ways how to concatenate Strings in a loop see #MadProgrammer's answer):
public static String getPreviewText(Member[] platoon) {
String s = platoon.length > 0 ? platoon[0].toString() : "";
for (int i = 1; i < platoon.length; i++)
s += "\n" + platoon[i].toString();
return s;
}
public static void setPreview(Member[] platoon) {
displayText.setText(getPreviewText(platoon));
}

Related

Adding result for each attempt in Java

I'm completely new to Java and need some help. I'm trying to add results for each attempt in a competition but I got stuck. So far I have the first part that works but without any results added and then I tried to find a way to add results while counting allowed attempts (which are different for each discipline) but without success. What would be the best way both to count attempts and to add results for each attempt?`
private void addResult() {
System.out.print("Enter the number of the participant you would like to add results for: ");
int number = scan.nextInt();
scan.nextLine();
while (number < 0) {
System.out.println("Error: must be greater than or equal to zero!");
number = scan.nextInt();
scan.nextLine();
}
System.out.print("Enter the name of the event you would like to see results for: ");
String event = scan.nextLine();
Participant p = findParticipantByNumber(number);
Event e = findEventByName(event);
if (p == null) {
System.out.println("No participant with number " + number + " found!");
} else if (e == null) {
System.out.println("No event called " + event + " found!");
} else {
System.out.print("Results for " + p.getFirstName() + " " + p.getLastName() +
" from " + p.getTeam() +
" in " + e.getEventName() + ":" + " " + p.getResult() );
scan.nextLine();
Result r = new Result(e, p);
p.addResult(r);
}
}
I would store a HashMap of attempts as an instance variable in the Participant class, where the keys are Strings representing the events and the value corresponding to each key is the number of attempts so far for that event. You could call this map attemptsByEvent and have getter and setter methods for it in Participant. If you need, you can take a look at this page from TutorialsPoint about how to create and populate maps, and what they are.
You should also make a map that is accessible from within addResult() which has Strings representing the events as keys and the maximum allowed attempt for that event as the values. You could call this map attemptMaximums.
Then, you can modify your final block of code to check the number of attempts so far before adding the result. You should also increment the value in the Participant's map if you do add results for an attempt.
else {
System.out.print("Results for " + p.getFirstName() + " " + p.getLastName() +
" from " + p.getTeam() +
" in " + e.getEventName() + ":" + " " + p.getResult() );
scan.nextLine();
Result r = new Result(e, p);
int attempts = p.getAttemptsByEvent().get(e);
if(attempts < attemptMaximums.get(e)){
p.addResult(r);
p.getAttemptsByEvent().put(e, attempts+1);
}
}

Printing multiple strings from an array as a single string

I want to print multiple Strings from an Array utilizing a for-loop, it will print a full first and last name, but only once. Here's my method for doing this.
This is the output I get:
"firstName secondName, "
There should be mutliple full names being printed.
The problem here is that in each iteration, you create a new memory location for list and so every time the loop executes, the value of list is overwritten. You can fix this by appending to list instead of changing the value of list in every iteration.
A side note, since Strings are immutable in java, for every iteration of the for loop, new memory will be allocated for list. This is not very efficient. You should instead use StringBuilder which is mutable. It would look like this.
StringBuilder str = new StringBuilder(list);
Then you can append to str :
str.append("any string");
This is equivalent to str + "any string"
Using StringBuilder, memory will be allocated to str only once and all the changes will take in place which is much more efficient. And finally you want to return a String object so you can call the method toString() on the StringBuilder object to convert it back into a String.
So, finally it would look like this :
public String getTANames() {
StringBuilder str = new StringBuilder("");
for(int i = 0; i < TAList.length; i++){
str.append(TAList[i].first + " " + TAList[i].second + ", ");
}
return str.toString();
}
You are very close. The problem is you keep resetting list every time you iterate over TANames. Try this instead:
public String getTANames() {
String list = "";
for(int i = 0; i < TAList.length; i++){
list += TAList[i].first + " " + TAList[i].second + ", ";
}
return list;
}
The difference is this line here: list += TAList[i].first + " " + TAList[i].second + ", "; you are adding to list not setting list.
In your current code, every loop changes the value of the list variable. To fix the issue, replace the current = with the += as follows:
list += TAList[i].first + " " + TAList[i].second + ", ";
public String getTANames() {
String list = "";
for(int i = 0; i < TAList.length; i++){
list += TAList[i].first + " " + TAList[i].second + ", ";
}
return list;
}
Hope that helps.

Display 2 ArrayLists into a jTextArea one after another, multiple times depending on the data entered

So, I'm trying to display the data stored in 2 ArrayLists into a jTextArea. The first ArrayList contains a bar's location, name, and whether is there live music and food service. The second bar contains the type of liquor and corresponding amounts of each.
I'm trying to get it to display like this:
The (barLocation) bar is named: (barName)
Live music: (true or false)
Food service: (true or false)
(That's the first ArrayList, followed by the second)
Vodka: (amount)
Whiskey: (amount)
Rum: (amount)
Gin: (amount)
Brandy: (amount)
This works great, if I enter one bar. If I enter two or more I get a long list of the data entered in different combinations. So if I enter say two bars with their liquor amounts, I'll get like 20-30 different ones with different combinations, instead of just the two entered in the format above.
This is the code section I'm using to display the data:
for(int i=0; i<bars.size(); i++)
{
for(int j=0; j<liquors.size(); j++)
{
jTextAreaDisplay.append(jTextAreaDisplay.getText()
+ bars.get(i) + liquors.get(j) + "\n\n");
}
}
Now I know I'm doing something wrong with the for loop, and I've tried different approaches to it but I'm stuck. Any help would be greatly appreciated.
UPDATE
I have two classes for one bar and one for liquor. The amount for the liquor is the amount in stock, so: Vodka: 20 for example would be 20 bottles. Sorry for the misunderstanding.
Code for Classes:
class Bar
{
String barLoc, barName;
boolean music, food;
public Bar(String l, String n, boolean m, boolean f)
{
this.barLoc = l;
this.barName = n;
this.music = m;
this.food = f;
}
#Override
public String toString()
{
return "The " + barLoc + " bar is named: " + barName + "\nLive music: "
+ music + "\nFood Service: " + food;
}
}
class Liquor
{
//String[] liquor = {"Vodka", "Whiskey", "Rum", "Gin", "Brandy"};
String vodka, whiskey, rum, gin, brandy;
int vCount, wCount, rCount, gCount, bCount;
public Liquor(String vodka, String whiskey, String rum, String gin,
String brandy, int v, int w, int r, int g, int b)
{
this.vodka = vodka;
this.whiskey = whiskey;
this.rum = rum;
this.gin = gin;
this.brandy = brandy;
this.vCount = v;
this.wCount = w;
this.rCount = r;
this.gCount = g;
this.bCount = b;
}
#Override
public String toString()
{
return "\nLiquor currently in stock:\n" + vodka + ": " + vCount + "\n" +
whiskey + ": " + wCount + "\n" + rum + ": " + rCount + "\n" +
gin + ": " + gCount + "\n" + brandy + ": " + bCount;
}
}
You get every combination because you are going to loop each liquor for every bar.
What I suggest is that you refactor your code so that the list of liquor becomes a property of a bar.
for(int i=0; i<bars.size(); i++)
{
jTextAreaDisplay.append(jTextAreaDisplay.getText()
+ bars.get(i).toString() + bars.get(i).getLiquor.toString() + "\n\n");
}
Now you get for every bar, every liquor with price that is added for that bar.
The bar class will have the following implementation
public class Bar {
//your other code
private Liqour liqour;
public Liqour getLiqour(){ return liqour;}
// your other code
}
When you create the Liqour for a bar, make sure you initialize it.
Liqour is not a list, but an Object with properties, so you don't need to iterate it.

How do I return the string in this for loop?

I have this DieRolling class that we are making for AP Computer Science. This method is supposed to return all the numbers they have rolled in a "neat" manner. Here is the code:
public void printNum()
{
for (int i=0;i<100;i++)
{
System.out.println("Roll " + (i+ 1) + ": " + numbers[i]);
}
}
I need to return the whole for loop, but I cant figure out how.
What should I do?
Thanks!
(This is my first post on here so sorry if it is kind of messed up)
You should declare printNum as a String then result a concatenate of all strings.
public String printNum(final int pToPrint)
{
StringBuilder result = new StringBuilder();
for(int i = 0; i < pToPrint; i++)
result.append("Roll " + (i+ 1) + ": " + numbers[i] + System.lineSeparator());
return result.toString();
}
Then you would call for example System.out.println(printNum(100));
You could simply return the array...
public int[] printNum() {
// ...
return numbers;
}
If you want to format the result, you could use
public String printNum() {
// ...
Arrays.toString(numbers);
}
If you want to customise the format, you could use...
public String printNum() {
StringBuilder sb = new StringBuilder(128);
for (int i=0;i<numbers.length;i++)
{
System.out.println("Roll " + (i+ 1) + ": " + numbers[i]);
if (sb.length() > 0) {
sb.append(", ");
}
sb.append(numbers[i]);
}
return sb.toString();
}
Or if you're using Java 8
public String printNum() {
StringJoiner joiner = new StringJoiner(", ");
for (int i=0;i<numbers.length;i++)
{
System.out.println("Roll " + (i+ 1) + ": " + numbers[i]);
joiner.add(Integer.toString(numbers[i]));
}
return sb.toString();
}
You'll first need to change the return type from void to something reasonable. I suggest that you use either an array of int, since you apparently know that you'll be returning exactly 100 numbers, or an ArrayList<Integer> if that assumption is incorrect, fill up your array or List in the loop, and return it. AGain, you'll need to change the return type to be the type of whatever you decide to return.
Since this is homework, the details should be left to you.
You can return only one time from a function.
So if you want to return all numbers, you can return an array if that numbers.
Just create a String variable String result = ""; and at each loop add numbers to the string. result += "Roll " + (i+ 1) + ": " + numbers[i] + "\n";
Or something. But you for sure need to change your return type. For the above solution it should be String instead of void.

Issue Incrementing a Value Inside an ActionListener

I'm trying to increment/decrement a user score as appropriate inside a text field on a (very) basic GUI. How, I only succeed in decrementing even though there is proof my conditional works correctly. Here is the pertinent code; I can supply more as needed.
//buttons: array of JButtons
//scoretxt: JTextField holding the score
//name- object name stored as string in separate string array
//check- odd numbers pass incorrect, evens pass correct
//safe: JTextArea for output
for (int i = 0; i < 18; i++) {
final String myname = "" + (buttons[i].getClientProperty("name"));
final String myval = "" + (buttons[i].getClientProperty("value"));
final String corr = "" + (buttons[i].getClientProperty("check"));
buttons[i].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
safe.append(myname + " " + ("" + myval));
if (corr == "correct") {
safe.append(" " + corr + "\n");
scoretxt.setText("" + ((Integer.parseInt(scoretxt.
getText())) + 1));
} else {
safe.append(" " + corr + "\n");
scoretxt.setText("" + ((Integer.parseInt(scoretxt.
getText())) - 1));
}
}
});
mygui.add(buttons[i]);
}
I have tried various approaches but I always rely on scoretxt.getText() to pass a value. Any and all help is appreciated, thanks.
You should be using the equals() method to compare two strings.
corr.equals("correct");
Please refer to How do I compare strings in Java?

Categories

Resources