java swing: Query list of Jcombobox<String> - java

I am just beginning with Java and Java swing.
I am working on a small meal plan program to check that the user eats all types of proteins.
It has a Jcombobox for 2 meals a day.
Is there a way to query all boxes using a for loop?
I tried this but it's not liking it:
public LunchMenu() {
initComponents();
Hashtable<String, Integer> Proteins = new Hashtable<>();
Proteins.put("Beef", 0);
Proteins.put("Chicken", 0);
Proteins.put("Fish", 0);
Proteins.put("Pork", 0);
Proteins.put("None", 0);
}
/**
*
*/
public void runCheck() {
String[] comboBoxes = new String[14];
comboBoxes = {"MonLun", "MonDin", "TueLun", "TueDin", "WesLun", "WesDin", "ThuLun", "ThuDin", "FriLun", "FriDin", "SatLun", "SatDin", "SunLun", "SunDin"};
for (String str : comboBoxes) {
String temp;
temp = (String)str.getSelectedItem();
lunch.Lunch.Proteins[temp]++;
}
}

Related

Java most efficient way to assign data values to multiple key dependencies

What I'm trying to do: I have a set of golf club objects(~60 clubs). Depending on the club name and club level(1-10 levels), each one will have a different maxmultiplier and minmultiplier value associated with it that I will need to perform calculations.
What I've thought about:
Using switch statement for the club levels and a hashmap to pair the club name with an array of the multipliers in order to retrieve the correct values. Issue I have with this would be that I would have to create ~60 separate 2item arrays for the multipliers. Thought about 2d arrays and so forth but I'm at the point where it feels like I'm going in circles. I know I CAN get it to work through brute force but I'm trying to work on efficiency. Is there a way to set this up in a localized way(table-like structure) that would make it easy to retrieve?
Things to Note: Java is my first language,I'm trying to learn, I'm at the skill level where I can MAKE things work but am transitioning into learning best practices. So for answers If we could stick with basic/intermediate java ideas that would be appreciated. But after I get it working next step will be implementing serializable to store data outside the program and learning that, followed by storing information in a SQL database which ultimately seems the easiest in my mind using a table.
Here is some of my code:
/*
* Creates all the clubs to be used in the app
*/
public ClubSet() {
clubMap = new HashMap<String, String[]>(100, (float) 0.8);
clubMap.put("DRIVER", driverArray);//all the club names of driver type
clubMap.put("WOOD", woodArray);
clubMap.put("LONG", longArray);
clubMap.put("SHORT", shortArray);
clubMap.put("WEDGE", wedgeArray);
clubMap.put("ROUGH", roughArray);
clubMap.put("SAND", sandArray);
for (HashMap.Entry<String, String[]> entry : clubMap.entrySet()) {
for (String clubName : entry.getValue()) {
Club club = new Club(entry.getKey(), clubName);
this.put(club, club.getClubType());
}
}
}
/*
* Returns a set of all clubs according to clubtypre(e.g. Driver,Wood,Long
* Iron,etc)
*/
public HashSet<Club> getClubSet(String clubType) {
HashSet<Club> clubSet = new HashSet<Club>();
if (this.containsValue(clubType)) {
for (HashMap.Entry<Club, String> entry : this.entrySet()) {
if (entry.getValue().equalsIgnoreCase(clubType)) {
clubSet.add(entry.getKey());
}
}
}
return clubSet;
}
}
public class Club {
private String clubType;
private String clubName;
private int level;
private ImageIcon imageIcon;
private String rarity;
private double maxMultiplier;
private double minMultiplier;
private HashMap<String, String[]> rarityMap;
private final String[] starterArray = new String[] { "BEGINNER DRIVER", "BEGINNER WOOD", "BEGINNER LONG",
"BEGINNER SHORT", "BEGINNER WEDGE", "BEGINNER ROUGH", "BEGINNER SAND" };
private final String[] commonArray = new String[] { "ROCKET", "QUARTERBACK", "VIPER", "SNIPER", "BACKBONE",
"SATURN", "RUNNER", "CLAW", "DART", "SKEWER", "MACHETE", "DESERT STORM", "SAND LIZARD" };
private final String[] rareArray = new String[] { "EXTRA MILE", "ROCK", "BIG DAWG", "GUARDIAN", "GOLIATH",
"GRIZZLY", "APACHE", "THORN", "HORNET", "DOWN-IN-ONE", "RAPIER", "ROUGHCUTTER", "RAZOR", "NIRVANA",
"MALIBU", "HOUDINI" };
private final String[] epicArray = new String[] { "APOCALYPSE", "BIG TOPPER", "THOR'S HAMMER", "HORIZON",
"CATACLYSM", "HAMMERHEAD", "GRIM REAPER", "B52", "TSUNAMI", "KINGFISHER", "FALCON", "FIREFLY", "BOOMERANG",
"ENDBRINGER", "JUNGLIST", "OFF ROADER", "AMAZON", "CASTAWAY", "SAHARA", "SPITFIRE" };
public Club() {
this.clubType = null;
this.clubName = null;
this.level = 1;
rarity = null;
// maxMultiplier = 0;
// minMultiplier = 0;
}
public Club(String clubType, String clubName) {
this.clubName = clubName;
this.clubType = clubType;
this.level = 1;
if (Arrays.asList(starterArray).contains(clubName)) {
this.rarity = "STARTER";
} else if (Arrays.asList(commonArray).contains(clubName)) {
this.rarity = "COMMON";
} else if (Arrays.asList(rareArray).contains(clubName)) {
this.rarity = "RARE";
} else if (Arrays.asList(epicArray).contains(clubName)) {
this.rarity = "EPIC";
}
// setMultipliers(clubName);
}

Display labels of data [deep4j]

I would like to print the labels of traindata / testdata used in classification. Here is the definition of both inputs (using deep4j).
InputSplit[] inputSplit = fileSplit.sample(pathFilter, splitTrainTest, 1 - splitTrainTest);
InputSplit trainData = inputSplit[0];
InputSplit testData = inputSplit[1];
that are then transformed in DataSetIterator like this :
ImageRecordReader recordReader = new ImageRecordReader(height, width, channels, labelMaker);
recordReader.initialize(trainData, null);
trainIter = new RecordReaderDataSetIterator(recordReader, batchSize, 1, numLabels);
Then I want to print how many examples per labels where found in each iterator in this function :
public void print(DataSetIterator iter){
HashMap<String, Integer> hash = new HashMap<String, Integer>();
while(iter.hasNext()){
DataSet example = iter.next();
for(int i = 0 ; i<numLabels ; i++){
if(example.getLabels().getDouble(i)==1.){
String label = example.getLabelName(i);
if(hash.containsKey(label))
hash.put(label, hash.get(label)+1);
else
hash.put(label, 1);
}
}
}
for (String label: hash.keySet()){
System.out.println(" label : " + label.toString() + ", " + hash.get(label) + " examples");
}
}
The issue is that it displays only one example per label, whereas there should much more... And when I don't split my dataset using fileSplit.sample() the function displays the right number of examples.
Any suggestion ?
If you use a dataset you can use the toString() of the dataset.getFeatureMatrix() and dataset.getLabels()
If you want to print just the label counts, you can use dataset.labelCounts() I would look more at the dl4j javadoc:
http://deeplearning4j.org/doc

manipulate and sort text file

I am working on a project where I have been given a text file and I have to add up the points for each team and printout the top 5 teams.
The text file looks like this:
FRAMae Berenice MEITE 455.455<br>
CHNKexin ZHANG 454.584<br>
UKRNatalia POPOVA 453.443<br>
GERNathalie WEINZIERL 452.162<br>
RUSEvgeny PLYUSHCHENKO 191.399<br>
CANPatrick CHAN 189.718<br>
CHNHan YAN 185.527<br>
CHNCheng & Hao 271.018<br>
ITAStefania & Ondrej 270.317<br>
USAMarissa & Simon 264.256<br>
GERMaylin & Daniel 260.825<br>
FRAFlorent AMODIO 179.936<br>
GERPeter LIEBERS 179.615<br>
JPNYuzuru HANYU 197.9810<br>
USAJeremy ABBOTT 165.654<br>
UKRYakov GODOROZHA 160.513<br>
GBRMatthew PARR 157.402<br>
ITAPaul Bonifacio PARKINSON 153.941<br>
RUSTatiana & Maxim 283.7910<br>
CANMeagan & Eric 273.109<br>
FRAVanessa & Morgan 257.454<br>
JPNNarumi & Ryuichi 246.563<br>
JPNCathy & Chris 352.003<br>
UKRSiobhan & Dmitri 349.192<br>
CHNXintong &Xun 347.881<br>
RUSYulia LIPNITSKAYA 472.9010<br>
ITACarolina KOSTNER 470.849<br>
JPNMao ASADA 464.078<br>
UKRJulia & Yuri 246.342<br>
GBRStacey & David 244.701<br>
USAMeryl &Charlie 375.9810<br>
CANTessa & Scott 372.989<br>
RUSEkaterina & Dmitri 370.278<br>
FRANathalie & Fabian 369.157<br>
ITAAnna & Luca 364.926<br>
GERNelli & Alexander 358.045<br>
GBRPenny & Nicholas 352.934<br>
USAAshley WAGNER 463.107<br>
CANKaetlyn OSMOND 462.546<br>
GBRJenna MCCORKELL 450.091<br>
The first three letters represent the team.
the rest of the text is the the competitors name.
The last digit is the score the competitor recived.
Code so far:
import java.util.Arrays;
public class project2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] array = new String[41];
String[] info = new String[41];
String[] stats = new String[41];
String[] team = new String[41];
//.txt file location
FileInput fileIn = new FileInput();
fileIn.openFile("C:\\Users\\O\\Desktop\\turn in\\team.txt");
// txt file to array
int i = 0;
String line = fileIn.readLine();
array[i] = line;
i++;
while (line != null) {
line = fileIn.readLine();
array[i] = line;
i++;
}
//Splitting up Info/team/score into seprate arrays
for (int j = 0; j < 40; j++) {
team[j] = array[j].substring(0, 3).trim();
info[j] = array[j].substring(3, 30).trim();
stats[j] = array[j].substring(36).trim();
}
// Random stuff i have been trying
System.out.println(team[1]);
System.out.println(info[1]);
System.out.println(stats[1]);
MyObject ob = new MyObject();
ob.setText(info[0]);
ob.setNumber(7, 23);
ob.setNumber(3, 456);
System.out.println("Text is " + ob.getText() + " and number 3 is " + ob.getNumber(7));
}
}
I'm pretty much stuck at this point because I am not sure how to add each teams score together.
This looks like homework... First of all you need to examine how you are parsing the strings in the file.
You're saying: the first 3 characters are the country, which looks correct, but then you set the info to the 4th through the 30th characters, which isn't correct. You need to dynamically figure out where that ends and the score begins. There is a space between the "info" and the "stats," knowing that you could use String's indexOf function. (http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf(int))
Have a look at Maps.
A map is a collection that allows you to get data associated with a key in a very short time.
You can create a Map where the key is a country name, with value being the total points.
example:
Map<String,Integer> totalScore = new HashMap<>();
if (totalScore.containsKey("COUNTRYNAME"))
totalScore.put("COUNTRYNAME", totalScore.get("COUNTRYNAME") + playerScore)
else
totalScore.put("COUNTRYNAME",0)
This will add to the country score if the score exists, otherwise it will create a new totalScore for a country initialized to 0.
Not tested, but should give you some ideas:
public static void main(String... args)
throws Exception {
class Structure implements Comparable<Structure> {
private String team;
private String name;
private Double score;
public Structure(String team, String name, Double score) {
this.team = team;
this.name = name;
this.score = score;
}
public String getTeam() {
return team;
}
public String getName() {
return name;
}
public Double getScore() {
return score;
}
#Override
public int compareTo(Structure o) {
return this.score.compareTo(o.score);
}
}
File file = new File("path to your file");
List<String> lines = Files.readAllLines(Paths.get(file.toURI()), StandardCharsets.UTF_8);
Pattern p = Pattern.compile("(\\d+(?:\\.\\d+))");
List<Structure> structures = new ArrayList<Structure>();
for (String line : lines) {
Matcher m = p.matcher(line);
while (m.find()) {
String number = m.group(1);
String text = line.substring(0, line.indexOf(number) - 1);
double d = Double.parseDouble(number);
String team = text.substring(0, 3);
String name = text.substring(3, text.length());
structures.add(new Structure(team, name, d));
}
}
Collections.sort(structures);
List<Structure> topFive = structures.subList(0, 5);
for (Structure structure : topFive) {
System.out.println("Team: " + structure.getTeam());
System.out.println("Name: " + structure.getName());
System.out.println("Score: " + structure.getScore());
}
}
Just remove <br> from your file.
Loading file into memory
Your string splitting logic looks fine.
Create a class like PlayerData. Create one instance of that class for each row and set all the three fields into that using setters.
Keep adding the PlayerData objects into an array list.
Accumulating
Loop through the arraylist and accumulate the team scores into a hashmap. Create a Map to accumulate the team scores by mapping teamCode to totalScore.
Always store row data in a custom object for each row. String[] for each column is not a good way of holding data in general.
Take a look in File Utils. After that you can extract the content from last space character using String Utils e removing the <br> using it as a key for a TreeMap. Than you can have your itens ordered.
List<String> lines = FileUtils.readLines(yourFile);
Map<String, String> ordered = new TreeMap<>();
for (String s : lines) {
String[] split = s.split(" ");
String name = split[0].trim();
String rate = splt[1].trim().substring(0, key.length - 4);
ordered.put(rate, name);
}
Collection<String> rates = ordered.values(); //names ordered by rate
Of course that you need to adjust the snippet.

ArrayList elements aren't printed

I'm pretty new to java and what i'm trying to do is make a model for a catalog storing available products in a computer parts shop, using collections. My instructor asked for one instance of each product in the catalog. This is what i came up with:
import java.util.*;
public class AvailablesCatalog {
public AvailablesCatalog(List cat1) {
cat1 = new ArrayList();
Motherboard item1 = new Motherboard("MD4652", 1995, "Lenovo", 100.50, "Intel", 32, 5);
CPU item2 = new CPU("MD4652", 1995, "Lenovo", 100.50, 2.9, 6);
Graphics item3 = new Graphics("MD4652", 1995, "Lenovo", 100.50, "AMD", 6);
RAM item4 = new RAM("MD4652", 1995, "Lenovo", 100.50, "DDR2", 4, 1600);
HD item5 = new HD("MD4652", 1995, "Lenovo", 100.50, "SSD", 2.5, 750);
Monitor item6 = new Monitor("MD4652", 1995, "Lenovo", 100.50, "LED", 17.5, "1920x1080", "HDMI");
Keyboard item7 = new Keyboard("MD4652", 1995, "Lenovo", 100.50, "Wireless");
Mouse item8 = new Mouse("MD4652", 1995, "Lenovo", 100.50, "Laser", "Wireless");
Printer item9 = new Printer("MD4652", 1995, "Lenovo", 100.50, "Laser", "Colored");
cat1.add(item1);
cat1.add(item2);
cat1.add(item3);
cat1.add(item4);
cat1.add(item5);
cat1.add(item6);
cat1.add(item7);
cat1.add(item8);
cat1.add(item9);
}
public String toString(List cat1, int i) {
for(i=0; i<cat1.size(); i++) {
System.out.println(cat1.get(i).toString());
}
return "----------------------------------------------------";
}
}
Now, through the shop's mainApp that i'm using to to print the catalog, i have stored an instance of the AvailablesCatalog object type in a variable called av. This is the mainApp:
public class mainApp {
public static void main(String[] args){
/* Variables for Menu System and Sub Menu System */
int MainMenu;
String SubMenu;
String ReturnToMenu;
String SubMenuReturnToMenu;
List cat1 = new ArrayList();
AvailablesCatalog av = new AvailablesCatalog(cat1);
/* Displays menu system to console */
System.out.println("..............MENU...............");
System.out.println("..............1 View All Available Products..............");
System.out.println("..............2 View Orders...................");
System.out.println("..............3 View Sales...................");
System.out.println("..............0 Exit...................");
System.out.print("Please select an option: ");
Scanner sc = new Scanner(System.in);
MainMenu = sc.nextInt();
if(MainMenu == 1){
for(int i = 0; i < cat1.size(); i++) {
System.out.println(av.toString(cat1, i));
}
}
else if(MainMenu == 2) {
System.out.println("lol");
}
else if(MainMenu == 3) {
System.out.println("lol3");
}
else if(MainMenu == 4) {
System.exit(0);
}
}
}
Everything compiles smoothly, and when i run mainApp the menu shows up correctly. But when i press 1 to print the available products catalog, the programm simply ends. Options 2 and 3 are simply placeholders for now btw. Thanks in advance.
You are using two different Lists in your program.
The first one is cat1in your main method (is empty)
The second in your constructor (is filled in the constructor)
You override the reference with the new created list in the constructor and fill that one instead. This is garbage collected after the constructor is finished and no reference is pointing on it.
In the toString method you are printing the the list that is passed via parameter which is the one from main (and empty).
Remove the cat1 = new ArrayList(); line from the constructor. Then it should work.

Selectable alternative to JOptionPane.showMessageDialog

Backgorund info:
I have a buddy of mine in the Navy, and he wanted to know if I could whip him up a small app that would calcualte when he has his guard duty, because apparently counting on a calendar is hard. I used JOptionPane.showMessageDialog to give him the output of the dates. Here's how I'm doing that.
GregorianCalendar knownDate = new GregorianCalendar(year,month,day);
GregorianCalendar[] futureDates = new GregorianCalendar[10];
for(int i = 0; i < 10; i++) {
futureDates[i] = new GregorianCalendar(year,month,day);
futureDates[i].add(Calendar.DAY_OF_MONTH,10*(i+1)); // duty every 10 days
}
String newline = System.getProperty("line.separator");
StringBuilder sb = new StringBuilder("Jakes duty dates:").append(newline);
for(GregorianCalendar d : futureDates) {
sb.append(months[d.get(Calendar.MONTH)]).append(" ");
sb.append(d.get(Calendar.DAY_OF_MONTH)).append(newline);
}
JOptionPane.showMessageDialog(null,sb.toString());
The 'only problem' is you can't select the text that is displayed. He'd like to select it for IM and email, because what's the point in only being half lazy, right? (Only problem is in quotes because I have a feeling he'll scope creep this to death... haha)
My question:
Is there a "one-line solution" to making a selectable showMessageDialog?
I was able to build on trashgod's answer. While he suggested using a JList, I'm instead using a JTextArea (which gives the kind of selection I need.)
Here's what I'm doing:
JTextArea text = new JTextArea(sb.toString());
JOptionPane.showMessageDialog(null,text);
And it's working like a charm!
================================================
After a little experimentation I did this:
DefaultListModel model = new DefaultListModel();
for(GregorianCalendar g : futureDates) {
String m = months[g.get(Calendar.MONTH)];
String d = String.valueOf(g.get(Calendar.DAY_OF_MONTH));
model.addElement(m + " " + d);
}
JList jlist = new JList(model);
JOptionPane.showMessageDialog(null,jlist);
JOptionPane.showMessageDialog(null,jlist.getSelectedValue());
And the second box displayed what I had selected on the first one. I was really impressed with that. Now granted, this isn't the functionality I was going for (the top section is) but that doesn't make it any less awesome! :-)
Add the dates to a DefaultListModel, create a JList, and pass the list to showMessageDialog(). It's more than one line, but the selection copies to the clipboard using the platform's copy keystroke.
private static final DateFormat df = new SimpleDateFormat("dd-MMM");
private static void createAndShowGUI() {
DefaultListModel dlm = new DefaultListModel();
for (int i = 0; i < 10; i++) {
GregorianCalendar knownDate = new GregorianCalendar();
knownDate.add(Calendar.DAY_OF_MONTH, 10 * i);
dlm.add(i, df.format(knownDate.getTime()));
}
JList list = new JList(dlm);
JOptionPane.showMessageDialog(null, list);
}

Categories

Resources