Java: Calling a class within a for loop - java

I've just started learning Java, so I apologize if this question is somewhat basic, and I'm sure my code is not as clean as it could be. I've been trying to write a small quiz program that will input a list of German verbs from a txt file (verblist.txt). Each line of the text file contains five strings: the German verb (verbger), the English translation (verbeng), the praeteritum and perfekt conjugations conjugations (verbprae and verbperf) and whether it uses haben or sein as the auxiliary verb (H or S, stored as verbhaben). The verb set is chosen by generating a random number and selecting the "row" of the two dimensional array. The GUI then displays the first two variables, and the user has to input the last three. If the last three match the values in the txt file, the user gets it correct and moves on to another verb.
I'm at the point where the code is working the way I want it to - for one verb. The way I've been organizing it is in two classes. One, VerbTable, imports the text file as a two dimensional array, and the other, RunVerb, generates the GUI and uses an ActionListener to compare the user input to the array. What I can't figure out now is how, after the user gets one verb set correct, I can then loop through the entire set of verbs.
I was thinking of creating a for loop that loops through the number of rows in the text file (saved in the code as height), generating a new random number each time to select a different verb set (or "row" in the two dimensional array.) Essentially, I'd like to get a loop to run through the entire VerbRun class, and pause for the ActionListener, until all of the verb sets have been displayed.
Here is the VerbTable class, which generates the array and random number to select the row:
package looptest;
import java.io.*;
import java.util.*;
public class VerbTable {
public int width;
public int height;
public int randnum;
public String verbger = new String("");
public String verbeng = new String("");
public String verbprae = new String("");
public String verbperf = new String("");
public String verbhaben = new String("");
public VerbTable() {
File file = new File("verblist.txt");
try {
/* For array height and width */
Scanner scanner1 = new Scanner(file).useDelimiter("\n");
int height = 0;
int width = 0;
while (scanner1.hasNextLine()) {
String line = scanner1.nextLine();
height++;
String[] line3 = line.split("\t");
width = line3.length;
}
System.out.println("Height: " + height);
System.out.println("Width: " + width);
this.width = width;
this.height = height;
/* Array height/width end */
/* random number generator */
int randnum1 = 1 + (int)(Math.random() * (height-1));
this.randnum = randnum1;
/* random number generator end */
Scanner scanner = new Scanner(file).useDelimiter("\n");
String verbtable[][];
verbtable = new String[width][height];
int j = 0;
while (scanner.hasNextLine()){
String verblist2 = scanner.next();
String[] verblist1 = verblist2.split("\t");
System.out.println(verblist2);
verbtable[0][j] = verblist1[0];
verbtable[1][j] = verblist1[1];
verbtable[2][j] = verblist1[2];
verbtable[3][j] = verblist1[3];
verbtable[4][j] = verblist1[4];
j++;
}
this.verbger = verbtable[0][randnum];
this.verbeng = verbtable[1][randnum];
this.verbprae = verbtable[2][randnum];
this.verbperf = verbtable[3][randnum];
this.verbhaben = verbtable[4][randnum];
}
catch (FileNotFoundException e){
e.printStackTrace();
}
}
public int getRand(){
return this.randnum;
}
public int getWidth(){
return this.width;
}
public int getHeight(){
return this.height;
}
public String getVerbger(){
return this.verbger;
}
public String getVerbeng(){
return this.verbeng;
}
public String getVerbprae(){
return this.verbprae;
}
public String getVerbperf(){
return this.verbperf;
}
public String getVerbhaben(){
return this.verbhaben;
}
public static void main(String[] args) throws IOException {
}
}
And here is the RunVerb class:
package looptest;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class RunVerb extends JFrame {
VerbTable dimensions = new VerbTable();
int width = dimensions.getWidth();
int height = dimensions.getHeight();
int randnum = dimensions.getRand();
String verbgerin = dimensions.getVerbger();
String verbengin = dimensions.getVerbeng();
String verbpraein = dimensions.getVerbprae();
String verbperfin = dimensions.getVerbperf();
String verbhabenin = dimensions.getVerbhaben();
String HabenSeinSelect = new String("");
public JTextField prae = new JTextField("",8);
public JTextField perf = new JTextField("",8);
public JLabel verbger = new JLabel(verbgerin);
public JLabel verbeng = new JLabel(verbengin);
public JRadioButton haben = new JRadioButton("Haben");
public JRadioButton sein = new JRadioButton("Sein");
public RunVerb() {
JButton enter = new JButton("Enter");
enter.addActionListener(new ConvertBtnListener());
prae.addActionListener(new ConvertBtnListener());
perf.addActionListener(new ConvertBtnListener());
JPanel content = new JPanel();
content.setLayout(new FlowLayout());
content.add(verbger);
verbger.setBorder(BorderFactory.createEmptyBorder(15, 20, 15, 20));
content.add(verbeng);
verbeng.setBorder(BorderFactory.createEmptyBorder(15, 20, 15, 40));
content.add(new JLabel("Praeteritum:"));
content.add(prae);
content.add(new JLabel("Perfekt:"));
content.add(perf);
content.add(haben);
haben.setBorder(BorderFactory.createEmptyBorder(0, 20, 0, 10));
haben.setSelected(true);
content.add(sein);
sein.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 10));
ButtonGroup bg = new ButtonGroup();
bg.add(haben);
bg.add(sein);
content.add(enter);
setContentPane(content);
pack();
setTitle("Verben");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}
class ConvertBtnListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String outprae = prae.getText();
int praenum = 0;
if (outprae.equals(verbpraein)){
praenum = 1;
}
String outperf = perf.getText();
int perfnum = 0;
if (outperf.equals(verbperfin)){
perfnum = 1;
}
boolean habenselect = haben.isSelected();
boolean seinselect = sein.isSelected();
if (habenselect == true){
HabenSeinSelect = "H";
}
else {
HabenSeinSelect = "S";
}
int habennum = 0;
if (HabenSeinSelect.equals(verbhabenin)) {
habennum = 1;
}
int numtot = praenum + perfnum + habennum;
if (numtot == 3){
System.out.println("Correct.");
}
else{
System.out.println("Incorrect.");
}
numtot = 0;
}
}
public static void main(String[] args) {
window.setVisible(true);
}
}
So what would be the best way to cycle through the entire verbtable array until all of the rows have been displayed? Should I create a for loop, and if so, where should it go? Should I make a new class that contains the loop and references the VerbRun class? If so, what would be the best way to go about it?
I hope this makes sense! Thank you!

To go through all the verbs exactly in a random order, you may not want to generate random numbers each time, as the random number can repeat. You have to create a random permutation of verbs, one way to do it is Collections.shuffle
see http://download.oracle.com/javase/6/docs/api/java/util/Collections.html
Also You dont have to create a new RunVerb Object, instead create once, and use setters to change the UI, and the functionality of Action Listeners. So pseudo code would be
Collections.shuffle(verbsList);
for(verb : verbsList)
{
setLabel1(verb[0]);
setLabel2(verb[1]);...
}

I would have a method like getNextRandomVerb() in then VerbTable class that generates the next verb to be shown. It will keep track of the verbs that have been shown ( for a given user-session ofcourse ) already and ensure the next one picked is not a repeat. Your RunVerb class seems to more responsible for managing the GUI , so this is not the place to define how to get the next verb to display.

Related

Can I write this code without using serialization?

For my project I was wondering whether there is a way I can do this assignment without using serialization. Here are the guidelines to the project and the code I already have together:
The Canadian Forest Service wants to do a simple simulation of the growth and pruning of forests. Each forest has a name and exactly 10 trees. The trees are planted when they are 1' to 5' tall, and each tree has a individual growth rate of 50%-100% per year. For the simulation new trees are constructed randomly within these bounds. A forest is reaped (by lumberjacks) on demand - all trees above a specifed height are cut down and replaced with new trees.
The user interface to the simulation must allow the user to:
Display the current forest (with tree heights to 2 decimal places)
Discard the current forest and create a new forest
Simulate a year's growth in the current forest
Reap the current forest of trees over a user specified height, replacing the reaped trees with random new trees.
Save the information about the current forest to file (named after the forest)
Discard the current forest and load the information about a forest from a file.
Class1
import java.io.*;
import java.util.*;
public class Forest{
//constants
private static final int MAX_NUM_TREES = 10;
//variables
int index;
private String name;
private Tree[] arrayOfTrees;
public Forest(String forestName){
//Constructor class that takes a name and creates an array of trees().
index = 0;
name = forestName;
arrayOfTrees = new Tree[MAX_NUM_TREES];
for(index = 0; index < arrayOfTrees.length; index++){
arrayOfTrees[index] = new Tree();
}
}
public void display(){
// displays the array of trees and the index
index = 0;
if(name != null){
System.out.println(name);
for(index = 0; index < arrayOfTrees.length; index ++){
System.out.printf("%2d : %s\n", (index + 1), arrayOfTrees[index]);
}
}else{
System.out.println("No forest.");
}
}
public void yearGrowth(){
//grows each tree in the array
index = 0;
for(index = 0; index < arrayOfTrees.length ; index ++){
arrayOfTrees[index].grow();
}
}
public void reap(int reapHeight){
//reaps the trees and prints out the old and new information
index = 0;
for(index = 0; index < arrayOfTrees.length; index++){
if(arrayOfTrees[index].getHeight() >= reapHeight){
System.out.println("Cut " + (index+1) + " : " + arrayOfTrees[index] );
arrayOfTrees[index] = new Tree();
System.out.println("New " + (index+1) + " : " + arrayOfTrees[index] );
}
}
}
public static void saveForest(Forest forest) throws IOException {
//saves the forest
String name = forest.getName();
ObjectOutputStream toStream;
toStream = new ObjectOutputStream(new FileOutputStream(name));
toStream.writeObject(forest);
toStream.close();
}
public static Forest loadForest(String fileName) throws IOException {
//loads the forest
ObjectInputStream fromStream = null;
Forest local;
fromStream = new ObjectInputStream(new FileInputStream(fileName));
try {
local = (Forest)fromStream.readObject();
}catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
return(null);
}finally{
try {
if (fromStream != null) {
fromStream.close();
}
} catch (IOException e) {
System.out.println(e.getMessage());
return(null);
}
}
return(local);
}
public String getName(){
return (name);
}
}
Class2
import java.util.Random;
import java.util.*;
import java.io.*;
public class Tree{
//creates the variables as the
private double height;
private double growthRate;
private static Random rand = new Random();
final double MIN_HEIGHT = 1;
final double MIN_GROWTH_RATE = 0.5;
final double MAX_HEIGHT = 5;
final double MAX_GROWTH_RATE = 1.0;
public Tree() {
//creates tree with a height and a growth rate
Random rand = new Random();
height = (MIN_HEIGHT + ((Math.random() * (MAX_HEIGHT - MIN_HEIGHT))));
growthRate = (MIN_GROWTH_RATE + (Math.random() * (MAX_GROWTH_RATE - MIN_GROWTH_RATE)));
}
public double grow(){
//tree grows and returns height
height = height * (1 + growthRate);
return height;
}
public double getHeight(){
return (height);
}
public double getGrowthRate(){
return (growthRate);
}
public String toString(){
//toString formats the output with height and growthrate
return (String.format("%7.2f (%2d%% pa)", height, ((int)(growthRate * 100))));
}
}
If by serialization you understand standard java serialization with ObjectXXXStream, then yes, you can avoid it.
If you mean serialization in more broad way, then no. Files cant directly store java objects you have to convert them to bytes (which is serialization by definition).
PS: If you actually ask "How?" you should include it in your question.

Counting number of times words show up in txt file Java

This program is suppsoed to count the number of times each word shows up in a .txt file
I'm on the right track because this program shows every word in the file in a text area but I need it to not repeat words and increment a counter instead. Am I on the right track under the for each word:words statement? I know that I just need some more logic in this statement but am not sure how to implement it. I should probably add that I'm using orderedlinkedlists to put all the words in alphabetical order in the text area so they or in order next to eachother.
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.util.Scanner;
public class Oct29 extends JPanel
{
private OrderedList<String> words;
private String filename;
private int width = 800;
private int height = 600;
private TextArea textarea;
public Oct29()
{
Scanner scan;
textarea = new TextArea("",0,0,TextArea.SCROLLBARS_VERTICAL_ONLY);
textarea.setFont(new Font("Helvetica",Font.PLAIN,24));
textarea.setPreferredSize(new Dimension(width,height));
setPreferredSize(new Dimension(width,height));
add(textarea);
JFileChooser chooser = new JFileChooser("../Text");
int returnvalue = chooser.showOpenDialog(null);
if(returnvalue == JFileChooser.APPROVE_OPTION)
{
try
{
File file = chooser.getSelectedFile();
filename = file.getName();
System.err.println(filename);
scan = new Scanner(file);
}
catch (IOException e)
{
System.err.println("IO EXCEPTION");
return;
}
}
else
{
return;
}
words = new OrderedLinkedList<String>();
while(scan.hasNext())
{
String token = scan.next().toLowerCase();
token = token.replace(",","").replace(".","");
words.add(token);
}
scan.close();
textarea.append(" "+filename+" has wordcount: "+words.size()+
"\n-------------------------\n\n");
for(String word : words)
{
for( int i=0;i<words.size(); i++)
{
int x =0; // This does not work but I'm trying to find if I'm on the right track
if(x < words.size())
textarea.append(word+"\n"); // THIS BY ITESELF WITHOUT THE INNER FOR LOOP WORKS FINE FOR DISPLAYING THE WORDS IN A TEXT AREA.
x++;
}
}
}
public static void main(String[] arg)
{
JFrame frame = new JFrame("Oct 29");
frame.getContentPane().add(new Oct29());
frame.pack();
frame.setVisible(true);
}
}
I would recommend trying another technique :
How many times a word appears in a TXT file
This may be useful as well:
Count the amount of times a string appears in a file
You can use a Map for your problem. It can map your keys (in your case these are the words) to values (integer values reflecting the occurrence of those words). You can initialize your map as follows:
Map<String, Integer> wordCount=new HashMap<String, Integer>();
Inside the loop you have to check that whether the map already contains that key (the word). If so, then you have to increment the value of the integer associated with it. If it is not added, just add that pair to the map with the value of the integer set to 1.

Adding data to a program if exist; else do generate random data in java

I have a math program that shows random math problems, when you click to see the next answer the next answer appears.
I have added a method which uploads a file called upload.txt
I want my program to run the math problems in this file instead of running the random
math problems if the file exist. If not I want the program to run the current way which is running the random math problems.
My current method for adding the text file is not 100 percent accurate.
I wont to just take the problems written in the file to be added. I got it working just uploading numbers to the command prompt by using code from another thread on StackOverflow.
random math problems class
import java.util.Random;
public class MathProblems {
private static final int MAX_NUMBER = 1000;
private static final Random random = new Random();
private double expected = 0;
private String question = "";
public void run() {
final int a = random.nextInt(MAX_NUMBER);
final int b = random.nextInt(MAX_NUMBER);
final int type = random.nextInt(4);
switch (type) {
case 0:
add(a, b);
break;
case 1:
subtract(a, b);
break;
case 2:
multiply(a, b);
break;
case 3:
divide(a, b);
break;
}
}
private void add(final int a, final int b) {
expected = a + b;
askQuestion(a + " + " + b + " = ");
}
private void subtract(final int a, final int b) {
expected = a - b;
askQuestion(a + " - " + b + " = ");
}
private void multiply(final int a, final int b) {
expected = a * b;
askQuestion(a + " * " + b + " = ");
}
private void divide(final int a, final int b) {
expected = (double)a / b;
askQuestion(a + " / " + b + " = ");
}
private void askQuestion(final String question) {
this.question = question;
}
public String getQuestion() {
return question;
}
#Override
public String toString(){
return Double.toString(expected);
}
}
Driver Class
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;
import javax.swing.*;
public class Driver extends MathProblems {
MathProblems problems = new MathProblems();
Scanner textfile;
String s = "Welcome Students!";
String b = "Start!";
private JFrame f;
private JPanel p;
JFrame frame = new JFrame();
JButton b1 = new JButton(b);
JLabel jl = new JLabel(s);
int i;
private int clicked;
public Driver() {
gui();
}
public void gui() {
f = new JFrame("Flash Card Program");
p = new JPanel();
f.setLayout(new GridLayout(2, 1));
f.add(jl);
f.add(p);
p.setLayout(new GridLayout(2, 1));
p.add(b1);
jl.setHorizontalAlignment(JLabel.CENTER);
// pack the frame for better cross platform support
f.pack();
// Make it visible
f.setVisible(true);
f.setSize(500, 400); // default size is 0,0
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (b1.getText().equals("Click For Answer")) {
jl.setText(problems.toString());
b = "Next Question";
b1.setText(b);
} else {
problems.run();
jl.setText(problems.getQuestion());
b = "Click For Answer";
b1.setText(b);
}
}
});
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (clicked++ == 10) {
Object[] options = { "No, thanks", "Yes, please" };
int response = JOptionPane.showOptionDialog(frame,
"Would you like more math questions? ",
"Math Questions", JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE, null, options,
options[1]);
if (response == 1)
clicked = 0; // reset
else
System.exit(0);
}
}
});
}
static void filereader(Scanner textfile) {
int i = 0;
int sum = 0;
while(i <= 19)
{
int nextInt = textfile.nextInt();
System.out.println(nextInt);
sum = sum + nextInt;
i++;
}
}
public static void main(String[] args) throws IOException {
EventQueue.invokeLater(new Runnable() {
public void run() {
new Driver();
Scanner textfile = null;
try {
textfile = new Scanner(new File("upload.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
filereader(textfile);
}
});
}
}
.txt file
1 + 1
2 + 2
3 + 3
4 + 4
5 + 5
6 + 6
7 + 7
8 + 8
9 + 9
10 + 10
You need to define a global vector of question values for each of a and b. A nicer way to do this is to define a class called "OneProblem" which has members for a, b, and op. You create a single 'Vector<OneProblem>' and as you read the file you create a OneProblem object for each line of the source. Then, at run time you either pick a random math problem, or loop through all the OneProblem objects, or you generate a completely random OneProblem from the random number generator. Something like:
class OneProblem {
public int a = 0;
public int b = 0;
public int op = 0;
public OneProblem(int _a, int _op, int _b) {
a =_a;
b = _b;
op = _op;
}
}
class MathProblems {
Vector<OneProblem> problems = new Vector<OneProblem>();
//...lot of your other code here as well....
workQuestion(OneProblem problem) {
switch (problem.op) {
case 0:
add(problem.a, problem.b);
break;
case 1:
subtract(problem.a, problem.b);
break;
case 2:
multiply(problem.a, problem.b);
break;
case 3:
divide(problem.a, problem.b);
break;
}
}
}
You file reader needs to read each line and parse the first and second values out of the line, as well as (I presume) the operand between them. Read the line, and search for the operand, and separate the integer before and the integer after. Then as you read each line, construct an instance of OneProblem to match each line. Now you are set to run.
When presenting the math questions, you loop through the values from i=0 to i<problems.size(). If there was no file read, those vectors will have no entries and so it will fall through. After you finish the vectors, or if the vectors are empty, present math questions with random values.
if (problems.size()>0) {
for (int i=0; i<problems.size(); i++) {
OneProblem selProblem = problems.get(i);
workQuestion(selProblem);
}
}
else {
workQuestion(new OneProblem({{random a}}, {{random op}}, {{random b}}));
}
Fill in the appropriate method for 'askQuestion'. This is represented above as a loop, but maybe you want to pick a random one of the test values for presentation? Then pick a reasonable random value for i in that range, and get the problem out of the vectors.
In your filereader method, you have this line, in a loop:
int nextInt = textfile.nextInt();
But the sample text that you show contains '+' characters between your numbers, and I see no code present to take that into account.
To fix, you can either define '+' as a delimiter on your Scanner object, or make sure your loop reads it as a string.

Java Sorting data from a file using JCheckboxes

I'm trying to create a program that will take data in from a random access file and sort it based on whichever checkbox the user selects. The data should be sorted by either the bank account number, customer name or balance (when a user clicks that checkbox the data in the text area becomes sorted based on that). Once the data is sorted, it is outputted into the JTextArea. I'm also trying to output the total amount of entries from the file in the text field below the check boxes.
Thanks!
import java.lang.reflect.Array;
import java.nio.file.*;
import java.text.DecimalFormat;
import java.util.Collections;
import java.io.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.*;
import javax.swing.border.Border;
public class GUIBankAcctSorter extends JFrame implements ItemListener {
public static void main(String[] args) {
GUIBankAcctSorter myFrame = new GUIBankAcctSorter();
myFrame.setVisible(true);
Path file = Paths.get("C:\\Java\\Bank.txt");
final String ID_FORMAT = "0000";
final String NAME_FORMAT = " ";
final int NAME_LENGTH = NAME_FORMAT.length();
final String BALANCE_FORMAT = "00000.00";
String delimiter = ",";
String s = ID_FORMAT + delimiter + NAME_LENGTH + delimiter + BALANCE_FORMAT + System.getProperty("line.separator");
final String EMPTY_ACCT = "0000";
String[] array = new String[3];
double balance = 0;
output(s, array, delimiter, balance, EMPTY_ACCT, file);
}
private static final long serialVersionUID = 1L;
private static final int WIDTH = 450;
private static final int HEIGHT = 310;
private static final int X_ORIGIN = 200;
private static final int Y_ORIGIN = 200;
JLabel title = new JLabel("Bank Account Sorter");
JLabel sort = new JLabel("Sort By ");
JLabel total = new JLabel("Total # of Bank Accounts ");
private Container con = getContentPane();
private FlowLayout layout = new FlowLayout();
static JTextArea area = new JTextArea(10, 35);
static JTextField field = new JTextField(5);
JCheckBox cust = new JCheckBox(" Cust # ", false);
JCheckBox bal = new JCheckBox(" Balance ", false);
JCheckBox name = new JCheckBox(" Name ", false);
public static void output(String s, String[] array, String delimiter, double balance, String EMPTY_ACCT, Path file){
String temp = "";
try{
InputStream iStream = new BufferedInputStream(Files.newInputStream(file));
BufferedReader reader = new BufferedReader(new InputStreamReader(iStream));
while(s != null){
array = s.split(delimiter);
if(!array[0].equals(EMPTY_ACCT)){
balance = Double.parseDouble(array[2]);
area.append("Cust # " + array[0] + "\t" + " Name: " + array[1] + " Balance " + "\t$" + array[2] + "\n");
}
s = reader.readLine();
}
reader.close();
}catch(Exception e){
System.out.println("Message: " + e);
}
field.setText(temp);
}
public GUIBankAcctSorter(){
super("Bank Account Sorter");
Font headFont = new Font("Arial", Font.BOLD, 28);
con.setLayout(layout);
title.setFont(headFont);
con.add(title);
area.setEditable(false);
field.setEditable(false);
con.add(new JScrollPane(area));
cust.addItemListener(this);
bal.addItemListener(this);
name.addItemListener(this);
con.add(sort);
con.add(cust);
con.add(bal);
con.add(name);
con.add(total);
con.add(field);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(X_ORIGIN, Y_ORIGIN, WIDTH, HEIGHT);
setResizable(false);
setLocationRelativeTo(null);
}
public void itemStateChanged(ItemEvent e) {
Object source = e.getSource();
int select = e.getStateChange();
if(source == cust){
if(select == ItemEvent.SELECTED){
bal.setSelected(false);
name.setSelected(false);
}
}
if(source == bal){
if(select == ItemEvent.SELECTED){
cust.setSelected(false);
name.setSelected(false);
}
}
if(source == name){
if(select == ItemEvent.SELECTED){
cust.setSelected(false);
bal.setSelected(false);
}
}
}
}
Here you can see a good example using comparator to sort the object.
Let us suppose:
RowTest is a class that represent a single row of grid.
orderAMT is a class variable/Column/JTextField of Row.
Now the code below show how to sort the List of RowTest according to its attribute orderAMT.
List<RowTest> sortedList = getAllRowsThatNeedToBeSorted();
Comparator comparator = new OrderAMTComparator();
Collections.sort(sortedList, comparator);
public class OrderAMTComparator implements Comparator<RowTest> {
#Override
public int compare(RowTest o1, RowTest o2) {
//Here you can use If condition to check which checkbox is selected and sort the list
//repace getOrderAMT with other fields.
BigDecimal compareRes = o1.getOrderAMT().getBigdecimalValue().subtract(o2.getOrderAMT().getBigdecimalValue());
//You can just return compareRes.compareTo(new BigDecimal(0))
//But Here I want to show that you can check any condition and return -1,1,0 as your
//requirement
if (compareRes.compareTo(new BigDecimal(0)) == -1) {
return -1;
} else if (compareRes.compareTo(new BigDecimal(0)) == 1) {
return 1;
} else if (compareRes.compareTo(new BigDecimal(0)) == 0 ) {
return 0;
}
return compareRes.intValue();
}
}
I hope you have understand this. If not I will elaborate.
Thankyou.
Is there anyway to do it with checkboxes?
Certainly:
Declare an Account class that stores the account number, name & balance.
Add each new Account to a List structure such as ArrayList.
Create a Comparator relevant to each of the 2 fields.
At time of sort, use Collections.sort(list,comparator).
Refresh the text area with the content of the sorted list.
Other tips
Since those check boxes are mutually exclusive, they should really be a ButtonGroup of JRadioButton instances.
Change setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); to setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); & setLocationRelativeTo(null) to setLocationByPlatform(true). See this answer for a demo.
Change setBounds(X_ORIGIN, Y_ORIGIN, WIDTH, HEIGHT); for pack() (& use layouts more effectively).

using a JButton actionperformed class how do I add elements from one arraylist to another arraylist?

I have a method that returns an arraylist which i am calling via a buttonListener. I need to be able to store each pushes resulting arraylist in another arraylist. How do I do this? Each time i try, it copies over the existing elements in the arraylist I'm using to keep track of push results.
private class ButtonListener implements ActionListener{
public void actionPerformed (ActionEvent e){
numCounter++;
String reqVal1 = requestor.getText();
int reqVal = Integer.parseInt(reqVal1);
request = reqVal;
requestsArray.get(3).set(0,0);
if(numCounter == 1){//---------------------------numCounter == 1 beginning-------- -------------------------
workingVar = memSize/2;
if(request>workingVar){
requestsArray.get(3).set(0,1);
}
else{
reqCounter++;
while (workingVar>=request){
workingVar = workingVar/2;
holes2.add(workingVar);
}
if(workingVar<request){
workingVar=workingVar*2;
holes2.add(workingVar);
holes2.remove(holes2.size()-2);
holes2.remove(holes2.size()-1);
}
}
e1=workingVar;
}//-----------------------------------------------end of numCounter == 1 section-------------------------------------
if(numCounter > 1){
for (int y = 0; y<requestsArray.get(0).size();y++){
if(requestsArray.get(1).get(y).equals("H")){
holes.add((Integer)requestsArray.get(0).get(y));
}
}
//BubbleSort of holes ArrayList
int in, out;
for(out= holes.size()-1; out>0;out--)
for(in =0; in<out;in++)
if(holes.get(in)<holes.get(in+1)){
int temp1 = holes.get(in+1);
int temp2 = holes.get(in);
holes.set(in, temp1);
holes.set(in+1, temp2);
}
//calculates the value of e1 using holes array
if(holes.isEmpty()){
requestsArray.get(3).set(0, 1);
}
else{
for(element=holes.size()-1;element>-1;element--){//starts at end of holes array loops backwards
e1 = holes.get(element); //assigns value of each element to e1
if(e1>=request) //if value e1 is greater than request stop looping
break;
}
workingVar=e1; //assign the value of e1 to workingVar
if (request>e1){
requestsArray.get(3).set(0, 1);
}
else{
//---------------------code for populating holes2 array---------------------------
reqCounter++;
if(workingVar!=request && workingVar/2>=request){
while (workingVar/2>=request){
workingVar = workingVar/2;
holes2.add(workingVar);
}
if(workingVar<request){
workingVar=workingVar*2;
holes2.add(workingVar);
}
}
}
}
}
//Sort of Holes2 ArrayList - reorder's holes2 for initial set up and subsequent inserts
int in, out;
for(out= holes2.size()-1; out>0;out--)
for(in =0; in<out;in++)
if(holes2.get(in)>holes2.get(in+1)){
int temp1 = holes2.get(in+1);
int temp2 = holes2.get(in);
holes2.set(in, temp1);
holes2.set(in+1, temp2);
}
//-------------------------------requestsArray Setups----------------------------------------------------
//Initial setup of requestsArray
if(numCounter == 1){
if(requestsArray.get(3).get(0).equals(0)){
requestsArray.get(0).set(0,e1);
requestsArray.get(1).set(0,"R");
requestsArray.get(2).set(0, reqCounter);;
for(int i = 0; i<holes2.size();i++){
requestsArray.get(0).add(holes2.get(i));
requestsArray.get(1).add("H");
requestsArray.get(2).add(0);
}
}
else{
requestsArray.get(0).set(0,e1);
requestsArray.get(1).set(0, "H");
requestsArray.get(2).set(0,0);
}
}
//Subsequent setup of requestsArray
int element2;
if(numCounter >1 && requestsArray.get(3).get(0).equals(0)){
for(element2 = 0; element2< requestsArray.get(0).size(); element2++){
if((Integer)requestsArray.get(0).get(element2)==e1 &&requestsArray.get(1).get(element2).equals("H") ){
break;
}
}
if(holes2.isEmpty()){
requestsArray.get(1).set(element2, "R");
requestsArray.get(2).set(element2, reqCounter);
}
else{ //holes2 is not empty
requestsArray.get(0).add(element2, workingVar);
requestsArray.get(2).add(element2,reqCounter);
requestsArray.get(1).add(element2, "R");
requestsArray.get(0).remove(element2+1);
requestsArray.get(2).remove(element2+1);
requestsArray.get(1).remove(element2+1);
for(int i = 1; i<holes2.size()+1;i++){
requestsArray.get(0).add(element2+i,holes2.get(i-1));
requestsArray.get(1).add(element2+i,"H");
requestsArray.get(2).add(element2+i,0);
}
}
}
//-----------------End Section for populating requestsArraywhen numCounter > 1---------------------------
//remove all values from holes1 and holes2
holes.clear();
holes2.clear();
System.out.println(results1);
ok. I have written a similar program that is simpler and easier to understand. Each time the button is pressed, the result is saved as an arrayList to another arrayList. Problem is it's appending it to the previous element. I need to be able to add the results of each press as a separate element. For example:
first press:
[5, 3, 5, 2, 6, 5]
second press would display:
[5, 3, 5, 2, 6, 5][2, 1, 4, 1, 4, 1]
This way I can loop through and get each array result separately. How do I do this?
public class mainClass{
public static void main(String[] args){
JFrame frame1 = new JFrame("testButton");
frame1.setDefaultCloseOperation(JFrame. EXIT_ON_CLOSE);
buttonExample b1 = new buttonExample();
frame1.getContentPane().add(b1);
frame1.pack();
frame1.setVisible(true);
}
}
public class Example {
private int rand1;
private ArrayList<ArrayList> count;
private ArrayList<Integer> count2;
private Random rnd;
private int counter1;
private ArrayList<ArrayList>count3;
public Example(){
count = new ArrayList<ArrayList>();
count2 = new ArrayList<Integer>();
rnd = new Random();
count3 = new ArrayList<ArrayList>();
}
private void addCount2(){
for(int x = 0; x<6;x++){
rand1 = rnd.nextInt(6)+1;
count2.add(rand1);// count2 == Integers
}
}
public void addCount(){
addCount2();
count.add(count2);// count == count3
}
public ArrayList<ArrayList> displayCount(){
return count;
}
}
public class buttonExample extends JPanel {
private JButton button1;
private Example example1;
public buttonExample(){
button1 = new JButton("Submit");
add(button1);
button1.addActionListener(new ButtonListener());
example1 = new Example();
}
private class ButtonListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
example1.addCount();
System.out.println(example1.displayCount().get(0));;
}
}
}
I would think about at least two solutions...
create a List<...> list which will last (global variable or something similar, depends on your needs) and use list.addAll() method
create a Map<String, List<...> map and than you can log your lists separately, your key might be a timestamp for example
Well, now when you posted the code you will have to start with a different thing - refactoring. Your code is very long, difficult to read and error prone. You have to think about it a little bit a rewrite it. And trust me, the more effort you put into your code at the beginning the better it will be at the end. Otherwise you may end up with an unmanagable code full of bugs...

Categories