Consultation about dynamically add to array - java

how to add unknow numbers of colors to this array ? for example i whant to add 6 colors
int[] colors = new int[] { Color.RED, Color.YELLOW, Color.BLUE,Color.GREEN };
and how to add unknow numbers of categorySeries ? for example i want to add 6 categorySeries
CategorySeries categorySeries = new CategorySeries("Vehicles Chart");
categorySeries.add("cars ", 30);
categorySeries.add("trucks", 20);
categorySeries.add("bikes ", 60);
categorySeries.add("plan ", 40);
thanks in advance

You can't add unknown numbers of items to an array, because arrays can't resize.
Use an ArrayList instead:
List<CategorySeries> categorySeriess = new ArrayList<CategorySeries>();
CategorySeries categorySeries = new CategorySeries("Vehicles Chart");
categorySeries.add("cars ", 30);
categorySeries.add("trucks", 20);
categorySeries.add("bikes ", 60);
categorySeries.add("plan ", 40);
categorySeriess.add(categorySeries);
And for the colors:
List<Integer> colors = new ArrayList<Integer>();
colors.add(Color.RED); // single add
colors.addAll(Arrays.asList(Color.YELLOW, Color.BLUE, Color.GREEN)); // bulk add

Consider using ArrayList, using it's add method and then calling toArray on it. This should work.

If you don't know how many items you want to keep track of, an array is probably not the best choice of data structure. I would recommend a linked list.
Check out java.util.LinkedList. You can use generic types to specify which kind of elements it should hold.
For example,
import java.util.LinkedList;
public class Test {
public static void main(String[] args) {
LinkedList<Integer> ll = new LinkedList<Integer>();
ll.push(1);
ll.push(2);
}
}
Alternatively, you could make the CategorySeries linked list with LinkedList<CategorySeries> ll = new LinkedList<CategorySeries>().

Related

Java how to calculate average of an arrayList that some elements removed randomly?

I have an arrayList<Integer> and arrayList<JLabel>. Integer holds the moneys as integers and JLabel holds the same values as strings. I want to remove randomly elements from both labels. For example if 20TL(tl is currency) removed in JLabel i want to remove it in integer arrayList too. It's simple. But then i want to calculate average of remains money in ArrayList. Here is my another arrayList to shuffle 0 to 23 numbers. Therefore i remove the same element both IntList and JLabel list.
ArrayList<Integer> Numbers = new ArrayList<Integer>();
for(int n = 0; n<24; n++){
Numbers.add(n);
}
Collections.shuffle(Numbers);
Then here is my both lists.
ArrayList<Integer> Money = new ArrayList<Integer>();
Money.add(1); Money.add(5); Money.add(10); Money.add(25); Money.add(50); Money.add(100); Money.add(500); Money.add(1000); Money.add(2000);
Money.add(5000); Money.add(10000); Money.add(20000); Money.add(25000); Money.add(30000); Money.add(40000); Money.add(50000); Money.add(100000); Money.add(200000);
Money.add(300000); Money.add(400000); Money.add(500000); Money.add(750000); Money.add(1000000); Money.add(2000000);
String[] para =new String[] {"1 TL","5 TL","10 TL","25 TL", "50 TL","100 TL","500 TL",//create an array for moneys
"1.000 TL","2.000 TL","5.000 TL","10.000 TL","20.000 TL","25.000 TL",
"30.000 TL","40.000 TL","50.000 TL","100.000 TL",
"200.000 TL","300.000 TL","400.000 TL","500.000 TL","750.000 TL"
,"1.000.000 TL","2.000.000 TL"};
ArrayList <JLabel> myLabel = new ArrayList<JLabel>();
for(int i=0; i < 12 ; i++){
JLabel holder = new JLabel();
holder.setText(para[i]);
myLabel.add(holder);
p2.add(holder);//add the label to the panel
}
for(int j=12; j<para.length; j++){
JLabel holder2 = new JLabel();
holder2.setText(para[j]);
myLabel.add(holder2);
p3.add(holder2);
}
here is my removing style.this in actionListener method
private int asd = 0;
///// some code
myLabel.get(Numbers.get(asd)).setVisible(false);
Money.remove(Numbers.get(asd));
When i try to remove money in intarraylist the calculation method does not work properly. Because for example if the Numbers array's first element is 5 then the 50 will be removed. And arrayList will be shrinked. After that when Numbers.get(asd) is equal to 23, there will not 23th element in int arraylist. Because its shrinked and has no such 23th element. I hope i can tell my problem well.
Ps: I've tried to use array instead of arraylist. But i can't calculate the average of lefts. Because array doesn't shrink when some element be removed.
I would make a lot of changes to that code. For one, I would try to create one collection of values, so that I don't have to fiddle with making changes to parallel collections, since I know that this would reduce the chance of errors. For something like this, I'd use a JList<Integer> and populate its model, a DefaultListModel<Integer> with integers. I can then easily display this as a Turkish Lira using a NumberFormat currency instance that is set to the Turkish Locale. For example if I create my model like so:
// constants used to populate my model
private static final Integer[] VALUES = { 1, 5, 10, 25, 50, 100, 500, 1000, 2000, 5000, 10000,
20000, 25000, 30000, 40000, 50000, 100000, 200000, 300000, 400000, 500000, 750000,
1000000, 2000000 };
// locale for Turkey used to get its currency
private Locale trLocale = new Locale("tr", "TR");
// currency number formatter for Turkish Lira
private NumberFormat tlFormat = NumberFormat.getCurrencyInstance(trLocale);
// my JList's model
private DefaultListModel<Integer> listModel = new DefaultListModel<>();
// create the JList with its model
private JList<Integer> jList = new JList<>(listModel);
// elsewhere in my constructor
// populate my list model with the array values
for (Integer value : VALUES) {
listModel.addElement(value);
}
// set my JList's renderer to render the numbers as Turkish Lira
jList.setCellRenderer(new MyCellRenderer());
// add my list to a JScrollPane and set how many rows are visible
jList.setVisibleRowCount(10);
JScrollPane scrollPane = new JScrollPane(jList);
The JList's cell renderer will change the value that it holds, here an Integer, to a String representation as Turkish Lira:
private class MyCellRenderer extends DefaultListCellRenderer {
#Override
public Component getListCellRendererComponent(JList<?> list, Object value, int index,
boolean isSelected, boolean cellHasFocus) {
String textValue = tlFormat.format(value); // format the Integer to its currency String
// pass it into the super's renderer
return super.getListCellRendererComponent(list, textValue, index, isSelected, cellHasFocus);
}
}
Then if later I can remove selected values from the list in a button's ActionListener and have it call a method that calculates the average of all items held in the list:
#Override
public void actionPerformed(ActionEvent e) {
List<Integer> selectedValues = jList.getSelectedValuesList();
for (Integer selectedValue : selectedValues) {
listModel.removeElement(selectedValue);
}
// method elsewhere that iterates through the listModel, calculates an average
// and displays it
calculateAndDisplayAverage();
}
It could look like so:
I would recommend a Map: i.e. HashMap<Integer, JLabel> money . Which would guarantee that your two data-sets are in sync.
For the average, Java 8 streams are really handy:
Collection<Integer> amounts = money.keySet();
double average = (double) amounts.stream().mapToInt(i -> i).sum() / amounts.size()

I need to make a reference to a JLabel based off a string

So I have numbered JLabels declared like so (In the class)
OP_1
OP_2
OP_3
etc..
And I have a number and a string.
What I want is that when, for example, the number is 2. I want to change the label text to the content of the string. This is part of a method that is supposed to take a string, put it into the last available JLabel, and then increment the number.
I am very confused, and help would be appreciated.
Here I created an array of JLabels and a method, updateNextLabel(String), which will update the next JLabel with whatever you enter for str.
public class Example {
static int count = 0; //Create a count
static JLabel[] array = new JLabel[3]; //Create an array to hold all three JLabels
public static void main(String[] args) {
//Set the default text for each JLabel
array[0] = new JLabel("This is OP1");
array[1] = new JLabel("This is OP2");
array[2] = new JLabel("This is OP3");
//Here is an example if you wanted to use a for-loop to update the JLabels
for (int x = 0; x < array.length; x++) {
updateNextLabel("This is the new text for OP" + (count + 1));
System.out.println(array[x].getText());
}
}
public static void updateNextLabel(String str) {
array[count].setText(str);
count++;
}
}
Instead of / additional to naming your labels by specific names you can later match them on, I'd think a Map of JLabels with Strings or Integers as keys might be a better approach:
Map<String,JLabel> labelMap = new HashMap<String,JLabel>();
labelMap.put("1", OP_1);
labelMap.put("2", OP_2);
This will allow later access of "The label for key 2" as well as "list me all that labels and find the one with text 2" as well

Pie chart using graphics 2d having trouble using arrays [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
import javax.swing.*;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
File file = new File(args[0]);
Scanner input = new Scanner(file);
int i = 0;
String names[] = null;
int slices[] = {};
while (input.hasNext()) {
names[i] = input.next();
slices[i] = input.nextInt();
i++;
}
JFrame f = new JFrame("Pie chart");
f.setSize(600, 350);
f.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
f.add(new PieChart());
f.setVisible(true);
}
}
Here is my second file...
import java.awt.*;
import javax.swing.*;
public class PieChart
extends JComponent {
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g.create();
Graphics2D g3 = (Graphics2D) g.create();
g3.setColor(Color.BLACK);
g2.setColor(Color.BLUE);
for (int i = 0; i < 5; i = i + 1) {
g2.fillRect(230, 20 * i + 50 , 20, 20);
g3.drawString("swallow", 255, 20 * i + 65);
g3.drawString("37.0%", 385, 20 * i + 65);
}
g2.fillArc(50, 50, 150, 150, 0, 360);
}
}
I am trying to read from a text file into two separate arrays. I want one array to hold the names and then one to hold the values. I then want to be able to then access the values from the array from my second file. My current problem is that it isn't accepting the input.next(); into the arrays for names[] and slices[]. How can I fix this?
Here is a sample text file:
swallow 10
magpie 5
fairywren 7
osprey 2
fantail 3
My current problem is that it isn't accepting the input.next(); into the arrays for names[] and slices[]. How can I fix this?
while (input.hasNext()) { should probably be while (input.hasNextLine()) {
You may then need to use input.nextLine() to get the actually text and use a second Scanner to parse the individual line
I am trying to read from a text file into two separate arrays. I want one array to hold the names and then one to hold the values. I then want to be able to then access the values from the array from my second file.
You should be passing the arrays to your PieChart class, maybe via the constructor.
You should also be calling super.paintComponent before doing any custom painting
It is giving me a NullPointerException error and it says it's on line 16 which is "names[i] = input.next();"
names is never initialised (is null)...
String names[] = null;
int slices[] = {};
Arrays are not dynamic, so unless you know in advance how many lines there are, it's not particular easy to manager.
In you case, assuming that the file doesn't change, you could use something like...
String names[] = new String[5];
int slices[] = new int[5];
Another choice would be to use a List of some kind or a Map, which are dynamic, so you don't need to know how many elements you might need before hand.
See Collections Trail for more details
String names[] = null;
You need to assign a non-null array to name before you can assign values to its elements; otherwise you will get the NullPointerException you observe.
However, you don't know how many elements you are going to need, so you should use a resizable data structure like an ArrayList.
Had you assigned {} to names like you did for slices, you'd get an ArrayIndexOutOfBoundsException, because it has no elements, but you are trying to assign a value to the zeroth one.
You should use an array if you know before you start adding items what the size of it will be (e.g. it will have 20 indices). Here, it seems that you don't know until runtime. So an array would not be the best data structure for this. Consider an array list instead.
ArrayList<String> names = new ArrayList()<String>;
while(...){
names.add(input.nextLine());
}
System.out.print(names.get(3)) //prints the 4th name

Fill ArrayList with colors for Android

I want to create 2 ArrayList. One holding 16 colors, the other one holding 139.
I have the list with colors (both RGB as 255,126,32 and Hex as 0xFFFF2552). I want to use the ArrayList to later pick random colors from.
I've tried int[], that doesn't work. I've tried ArrayList<Integer> and ArrayList<Color>. My problem is; I don't understand how to add the colors to the ArrayLists.
Thanks!!
For now, I'm exploring this:
Color cBlue = new Color(0,0,255);
Color cRed = new Color(255,0,0);
ArrayList colors = new ArrayList();
colors.add(cBlue);
colors.add(cRed);
and so on...
I really like int[] colors = = new int[] {4,5}; because it's only one line of code... but how do I get colors in, to later on, pick from?
or.. would it be better to store the colors in a strings.xml file and then fill the ArrayList from there? If so, how should I do that?
Thanks!!
You could try:
int[] colors = new int[] {Color.rgb(1,1,1), Color.rgb(...)};
For example, but I don't think it's a good idea to decide only using "one line" argument.
List<Integer> coloras = Arrays.asList(new Integer[]{Color.rgb(1, 1, 1), Color.rgb(...)});
Will also work.
You can create an arraylist in arrays.xml file:
<resources>
<string-array name="colors">
<item>#ff0000</item>
<item>#00ff00</item>
<item>#0000ff</item>
</string-array>
</resources>
Then use the loop to read them:
String[] colorsTxt = getApplicationContext().getResources().getStringArray(R.array.colors);
List<Integer> colors = new ArrayList<Integer>();
for (int i = 0; i < colorsTxt.length; i++) {
int newColor = Color.parseColor(colorsTxt[i]);
colors.add(newColor);
}
In my opinion keeping colors in the list is the most convinient solution.
To take a color from the list randomly, you do:
int rand = new Random().nextInt(colors.size());
Integer color = colors.get(rand);
I would make a text file or xml file populated with the color info and have a function that reads in each line of the file using a loop, creates a Color object for each line and adds it to the array list and then goes to the next line until there are no lines left.
I would recommend against using a configuration file unless you want to be able to change your colors without code changes. I suspect your colors are constant though, so the file would just add unnecessary complexity to your application.
The code sample in your question assumes java.awt.Color when you would actually use the utility class android.graphics.Color which cannot be instantiated.
Therefore I recommend the following solution as a static variable (and be careful not to modify the contents of the array later):
static final int[] colors16 = {
Color.rgb(255, 0, 0),
Color.rgb(0, 255, 0),
Color.rgb(0, 0, 255)
};
Now add a static instance of Random to use for selecting random colors from the list.
static final Random random = new Random();
And then pick your color!
int colorIndex = random.nextInt(colors16.size());
Color color = colors16.get(colorIndex);
If you feel it's important to protect the contents of your list, you can make it immutable as follows, at the small expense of boxing your color ints into Integer objects.
static final List<Integer> colors = Collections.unmodifiableList(
Arrays.asList(
Integer.valueOf(Color.rgb(255, 0, 0)),
Integer.valueOf(Color.rgb(0, 255, 0)),
Integer.valueOf(Color.rgb(0, 0, 255))
)
);
Technically you can leave out the Integer.valueOf() conversion in the above snippet and Java will autobox the ints.
You can also can use int[] colors = new int[]{color1.getRGB(),color2.getRGB()};
And decode using: Color color = new Color(colors[0]);
What you have looks like it makes sense, but you should specify the type of the ArrayList.
List<Color> colorList = new ArrayList<Color>();
colorList.add(cBlue);
... etc
(The difference between declaring it as a List or an ArrayList is that List is the interface that ArrayList implements. This is a generally pretty good practice, but for your purposes it probably won't make a difference if you declare it as a List or an ArrayList).
If you want to do it in fewer lines of code, you can use an ArrayList initializer block, like this:
List<Color> colorList = new ArrayList<Color> { new Color(...), cBlue };
Or with Arrays.asList, which takes in an array and returns a List.
But in general you should get used to verbosity with Java, don't try to optimize your lines of code so much as the performance of those lines.
(Sidenote: make sure you're using the correct Color class. There's android.graphics.Color and java.awt.Color, and they're totally different, incompatible types. The constructor you're using is from java.awt.Color, and with Android you're probably going to want to use android.graphics.Color).

java array of arraylists

I have four columns of buttons in my program. Buttons move between columns when assigned new ones. Instead of declaring 4 separate arraylists to store the buttons, is there a way to create 1 array of arraylists so I can simply itterate through the array?
I've tried List<JButton>[] lists = new ArrayList<JButton>[5];
But that won't work. What am I missing?
EDIT:
for(int i = 0; i < 5; i++){
if(choiceList.getSelectedIndex() == i){
if(btnPersons[nameList.getSelectedIndex()].getX() == column[i]){
JOptionPane.showMessageDialog(null, "Error - Name already present in the column.","", 1);
}else{
for(int j = 0; j < 5; j++){
if(lists[j].get(i) != null){
lists[j].remove(btnPersons[nameList.getSelectedIndex()]);
}
}
lists[i].add(btnPersons[nameList.getSelectedIndex()]);
lists[i].get(i).setBounds(column[i], ROWS[i], 125, 20);
//reloadLocations();
}
}
}
This is my code currently.Once a new column is selected it checks to see which listthe button was in and removes it, then adds it to the new list. But my new problem is that using lists[i] will no longer work. Idk how to properly loop through my list of arraylists using this declaration:
List<ArrayList<JButton>> lists = new ArrayList<ArrayList<JButton>>();
You have to keep a list of lists of JButton objects:
List<List<JButton>> lists = new ArrayList<List<JButton>>();
// populate (replace with your code)
lists.add(Arrays.asList(new JButton("list 1, button 1"), new JButton("list 1, button 2")));
lists.add(Arrays.asList(new JButton("list 2, button 3"), new JButton("list 2, button 4")));
lists.add(Arrays.asList(new JButton("list 3, button 5"), new JButton("list 3, button 6")));
lists.add(Arrays.asList(new JButton("list 4, button 7"), new JButton("list 4, button 8")));
// iterate
for(List<JButton> subList : lists) {
for(JButton button : subList) {
System.out.println(button.getText());
}
}
Giving an example of what worked for me / talked above.
List []oArrayOfArrayList = new ArrayList[2];
List<String> oStringList = new ArrayList<String>();
List<Integer> oIntegerList = new ArrayList<Integer>();
oArrayOfArrayList[0] = oStringList ;
oArrayOfArrayList[1] = oIntegerList ;
You cannot create arrays from classes with generic parameters.
You'll either want to make a list of a list, or forgo generic parameters.
You are not able to call the new operator for a generic object because at run time the type has been erased.
create a class for your ArrayList:
private class xxx extends ArrayList<JButton> {
// need serial to keep IDE happy
private static final long serialVersionUID = -2392107594926751233L;
};
private xxx[] lists = new xxx[5];

Categories

Resources