These questions might have really simple answers but in this code
public void setupYears()
{
ArrayList<String> years_tmp = new ArrayList<String>();
for(int years = Calendar.getInstance().get(Calendar.YEAR)-90 ; years<=Calendar.getInstance().get(Calendar.YEAR);years++)
{
years_tmp.add("Year"+years+"");
}
Y = new JComboBox(years_tmp.toArray());
Y.setLocation(404,310);
Y.setSize(250,25);
Y.setEditable(false );
firstPanel.add(Y);
}
How do I firstly reverse the years so the first year would be the current year and the last year would be 90 years ago instead of vice versa?
Also how would I put the "Year" as the first object in the JComboBox instead of "Yearxxxx"?
"xxxx" being whatever year is displayed in the JComboBox
To solve the ordering problem:
for(int years = Calendar.getInstance().get(Calendar.YEAR) ; years>=Calendar.getInstance().get(Calendar.YEAR)-90;years--)
And to put "Year" in the first box, simply add the line
years_tmp.add("Year");
before your for loop.
Hope this helps.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I'm trying to add all elements in my ArrayList but it seems quite a challenge. Tried different methods and functions but none of them worked. Here is my code:
for (Kids ki : GroupOfKids) {
try {
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date date = new Date();
String currentDate= dateFormat.format(date);
Date datum;
datum = dateFormat.parse(currentDate);
Date bornDate;
bornDate= ki.getbornDate();
int days = daysBetween(bornDate, datum);
//code above works fine..from here it's getting confusing
List<Integer> allKids;
allKids= new ArrayList<>();
allKids.add(days);
int total;
total = allKids.stream().mapToInt(Integer::intValue).sum();
System.out.print(total);
} catch (Exception e) {
e.printStackTrace();
}
}
I'm calculating how old are the "Kids" in days. I get an int and put the results in the ArrayList. I'm unable to get one result. I either get for each kid alone how old he/she is or I get both results if there are 2 for example stacked.
Example:
Kid 1 is 1234 days old
Kid 2 is 3422 days old
Result: 12343422
I expect 1234 + 3422 = 4656.
If there are more entries, then the sum of all together.
Can someone tell me where I'm making a mistake?
The first thing I see is using the old java.util.Date instead of the new java.time.LocalDate; then use the Period class to determine the number of days (probably could have modified your daysBetween if you had posted it). Like,
private static int getDaysOld(Date d) {
return Period.between(d.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(),
LocalDate.now()).getDays();
}
Then your stream should be used to map each Kids to their age and sum; like
int total = allKids.stream().mapToInt(k -> getDaysOld(k.getbornDate())).sum();
Let's say that you are doing sum in a wrong place.
You should define and initialize your list before the loop and do your summation after the loop ends.
List<Integer> allKids;
allKids = new ArrayList<>();
for( ... ) {
.
.
.
allKids.add(days);
.
.
.
}
int total;
total = allKids.stream().mapToInt(Integer::intValue).sum();
System.out.print(total);
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Removing an element from an Array (Java) [duplicate]
(15 answers)
Closed 4 years ago.
Got a simple auction program running, only problem is that if a user is removed before auction is closed his/hers bids are supposed to be removed. I dont have it 100% down yet but I think I am on the right path.
The bids have to be arrays and right now it is kinda removed or just moved maybe. This was a the error earlier.
Top Bid:[Wow 400 kr, Boy 311 kr, Man 33 kr, Dude 2 kr]
command>remove user
Name>wow
Wow has been removed from registry
command>list auctions
Auction # 1: Item. Top Bid:[Boy 311 kr, Man 33 kr, Exception in thread "main" java.lang.NullPointerException
public void removeBid(String name) {
for(int a = 0;a < bidIndex; a++) {
if(bids[a].getUser().getName().equals(name)) {
bids[a]=null;
bidIndex--;
break;
}
}
sortBids();
public void sortBids() {
if(bidIndex > 1) {
for(int a = 0; a < bidIndex -1; a++) {
for(int b = a + 1; b < bidIndex; b++) {
if(bids[a] == null || bids[a].getBid() < bids[b].getBid()) {
Bid temp = bids[a];
bids[a] = bids[b];
bids[b] = temp;
}
}
Arrays cannot change size once initialized. If you create an array new String[10]; it will forever have 10 items (which are null by default). Setting an index to null doesn't change this.
String[] items = new String[] {"String1", "String2", "String3"};
items[1] = null;
This arrays would now look like [String1, null, String3].
If you need to change arrays as much as it seems, you're better off using a List or Map.
I would suggest using a HashMap if you want to easily link one object to another. In this case it looks like you'd be linking a String (name) to the Bid object.
Map<String, Bid> bids = new HashMap<String, Bid>();
Bid bid1 = new Bid(/*...*/);
Bid bid2 = new Bid(/*...*/);
// Add bids to the map
bids.put("Wow", bid1);
bids.put("Boy", bid2);
// Get any of these objects
Bid retrievedBid = bids.get("Wow");
// Or remove them
bids.remove("Wow");
HashMaps are similar in concept to associative arrays from other languages, where you have a key -> value relationship. Each key is unique, but the value can repeat.
They can also be converted to arrays if the final result you need is an array.
Bid[] bidsArray = new Bid[0];
bidsArray = bids.values().toArray(bidsArray);
One way you can achieve this is to convert the array to a list and then remove the bid using Java streams and convert back.
List<Bid> bidsList = Arrays.asList(bids);
bidsList = bidsList.stream()
.filter(n -> !n.getUser().getName().equals(name))
.collect(Collectors.toList());
bids = bidsList.toArray(new Bid[bidsList.size()]);
This question already has answers here:
Questions about Java's String pool [duplicate]
(7 answers)
Closed 7 years ago.
It may sound so silly to ask but still I want to know what will happen if i assign value of string within for loop. Let's say
String name = " darsha" ;
for ( i = 0 ; i < 10 ; i ++ )
{
name = darsha ;
}
What will happen internally? Will there be only one name instance in string pool or 10
This will unnecessary utilize memory as well cpu of your machine.
As output going to ramain the same that name="darsha"
So unneccesary wasting of memory,cpu utilization 7 wastage of java heap nothing else.
String name = " darsha" ;
for ( i = 0 ; i < 10 ; i ++ )
{
name = "darsha" ;
}
yes there will only be ONE name instance. :)
and there is a mistake in your internal name as well. It should be corrected with inverted commas as the darsha is a string value. name = " darsha" ;
You must add int before "i" in the loop,and it should be " darsha", instead of just darsha,if you modify like that the last result is name = " darsha"
I'm a begginer programmer and my problem is I have no idea on how to put a list of years in a JComboBox from the current date to 80 years in the past. I could do a string like this,
String Y_tmp[]={"1934","1935","1936","1937"}; //-all the way to current year
JComboBox Y = new JComboBox(Y_tmp);
However that looks very messy and does not automatically change to the next year upon the new year.
It also does not remove the last year from the beggining of the list. Does anyone know how to do what I am wanting to do?
I use this, in the prop of combobox:
ArrayList<String> years_tmp = new ArrayList<String>();
for(int years = 1980; years<=Calendar.getInstance().get(Calendar.YEAR); years++) {
years_tmp.add(years+"");
}
jComboBox1 = new JComboBox(years_tmp.toArray());
Easiest way to do this is..
for(int i=1950;i<=2019;i++){
jComboBox3.addItem(i);
}
You are all done
Right I've got 3 model classes and 3 of those get data from the database (different tables) via SQL and save data into arraylists.
Now I'm trying to input three array lists data into the table.
The problem is that 2 array lists (closing and closing2) have got same amount of data and 1 array list has got only 4 values. What I want is that it would output in table as a 0 if the date from arraylist does not match date in other arraylists.
It is done by an IF statement that checks if dates are equal.
The problem is that arraylist closing1 has only got 4 values and it will not let to loop through all other arraylists more than 4 times.
The question is, how can I still keep looping through arraylists closing and closing 2 and start looping through arraylist closing1 from beginning?
try{
Model_Closing[] closing = Model_Closing.QueryWhere();
Model_Closing_DIV[] closing1 = Model_Closing_DIV.QueryWhere();
//Model_Closing_VisUnit[] closing2 = Model_Closing_VisUnit.QueryWhere();
model.setRowCount(0);
for(int i=0; i < closing.length; i++)
if (closing1[i].GetDate().equals(closing[i].GetDate())){
model.insertRow(i,new Object[]{date=closing[i].GetDate(),openingDollarBalance = closingDollarBalance,"NA",fundValue,dollarTransactionAmount,closing[i].GetNAV() * dollarTransactionAmount,visibleUnits,closingDollarBalance,closing[i].GetNAV(),dailyDivRate=closing1[i].GetDiv(),dailyDivDollars = dailyDivRate * accruedUnits,dailyDivRate / closing[i].GetNAV(), accruedDivDollars = accruedUnits * dailyDivRate,accruedUnits = visibleUnits + dailyDivUnits, });
}
else {
dailyDivRate = 0.0;
model.insertRow(i,new Object[]{date=closing[i].GetDate(),openingDollarBalance = closingDollarBalance,"NA",fundValue,dollarTransactionAmount,closing[i].GetNAV() * dollarTransactionAmount,visibleUnits,closingDollarBalance,closing[i].GetNAV(),dailyDivRate,dailyDivDollars = dailyDivRate * accruedUnits,dailyDivRate / closing[i].GetNAV(), accruedDivDollars = accruedUnits * dailyDivRate,accruedUnits = visibleUnits + dailyDivUnits, });
}
if (closingTable == null) {
closingTable = new JTable(model);
add(new JScrollPane(closingTable));
}
else{
closingTable.setModel(model);
}
}
catch(Exception ex){
JOptionPane.showMessageDialog(this,ex.getMessage(),"Error",JOptionPane.ERROR_MESSAGE);
}
The question is, how can i still keep looping through arraylists
closing and closing 2 and start looping through arraylist closing1
from begining?
I guess what you need is:
closing1[i%closing1.length].GetDate()== closing[i].GetDate()
Under another understanding of the question,
Date date1 = (i < closing1.size()) ? closing1[i].GetDate() : zero;
date1 == closing[i].getDate();
where zero is whatever date that will "output in table as a 0"