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
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);
I'm trying to make an android quiz game that randomizes my questions and an images to help answer the question.. but the random values does not return the same after 2 attempts in the game.. randomNum is the int that i used for getting random number.. i'd like both the question to sync..
Random random = new Random();
//get random number between 0 to 9.
int randomNum = random.nextInt(quizArray.size());
//image
imageView.setBackgroundResource(image[randomNum]);
//pick quiz
ArrayList<String> quiz = quizArray.get(randomNum);
//set question and answer
questionLabel.setText(quiz.get(0));
rightAnswer = quiz.get(1);
//remove question
quiz.remove(0);
Collections.shuffle(quiz);
//set Choices
btn1.setText(quiz.get(0));
btn2.setText(quiz.get(1));
btn3.setText(quiz.get(2));
btn4.setText(quiz.get(3));
//remove quiz from quizArray
quizArray.remove(randomNum);
}
When you remove the quiz from your quizArray with this quizArray.remove(randomNum); you need also to remove the related image from image[] table, i suggest that you use a List of image instead of table so you can also use image.remove(randomNum); after quizArray.remove(randomNum);
I hope this helps
as B.M said, it looks like you're removing the quiz from quiz array but you're not removing the image from the image array - this is causing their indexes to be off.
Maybe you want to try using a HashMap of (quiz, image), and then grab a pair from the map with the random index.
Why don't you create a Question class with fields for questionString, answerString, and image. Then you can create a list of Question objects and simply removing the Question from the list will remove all associated question data.
class Question {
public final String questionString;
public final String answerString;
public final byte[] image;
public Question(String question, String answer, byte[] image) {
questionString = question;
answerString = answer;
this.image = image;
}
}
...
List<Question> questions = new ArrayList<>();
//Populate questions however
//I would suggest reading the questions from an XML file
//Instead of static array declarations for ease of use in the future
System.out.println(questions);
questions.remove(0);
System.out.println(questions);
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have data type of the following format:
Popularity:xx
Name:xx
Author:xx
Sales:xx
Date Published: xx
I am free to choose whatever way I can store my data in.
I will need to perform some queries on the data, for example
What are the top 'N' Books for the year 'M'
What are the average sales of the top 'N' songs for author 'X'?
It should be kept in mind that further queries may be added.
What will be the different ways to represent the data to perform the queries (in Java)? What will be the merits?
Note: (Not looking for a DB solution)
JDK comes bundled with Java DB and seems perfectly fine for your use case.
Edit: Sorry I misread the question as a dB solution because it seems you need it. That said you should look for a DB solution where you just query your books from.
If you actually do want to perform queries on data-structures in memory you can use Apache Commons Collections which support filtering.
If you do want to use a data-structure like a Vector which seems like a solution, you need to build indexes to improve performance. Then lookup in the indices and get the book needed. If you know which searches are necessary you can group chosen indexes and create a block to easily search. Essentially creating your own cube data-structure. Could be a nice project.
Arraylist of a class. Create a class with those variables as, well, class variables, then instantiate an Arraylist of said object. Then you can perform searches based on the values of certain variables. For example:
//replace "ClassName" with the name of the class
ArrayList<"ClassName"> array = new ArrayList<"ClassName">();
ArrayList<"ClassName"> results = new ArrayList<"ClassName">();
for("ClassName" obj:array)
{
if(obj.getAuthor().equals("Author Name"))
{
results.add(obj);
}
}
There are many ways to sort the results, including using Collections.sort(); which seems to be the best way to go about it.
Sort ArrayList of custom Objects by property
EDIT: I went ahead and gave you an example based on the specific case you outlined in the comments. This should help you out a lot. As stated before, I had a similar issue for a lab in University, and this was a way I did it.
You could use a Bean to wrap your data:
public class Record {
int popularity;
String name;
String author;
int sales;
int yearPublished;
public Record(int popularity, String name, String author, int sales, int yearPublished) {
super();
this.popularity = popularity;
this.name = name;
this.author = author;
this.sales = sales;
this.yearPublished = yearPublished;
}
//getter and setter...
public String toString(){
return name;
}
And this is a typical usage querying with java8:
Record Record1 = new Record(10,"Record 1 Title","Author 1 Record",10,1990);
Record Record2 = new Record(100,"Record 2 Title","Author 2 Record",100,2010);
Record Record3 = new Record(140,"Record 3 Title","Author 3 Record",120,2000);
Record Record4 = new Record(310,"Record 4 Title","Author 1 Record",130,2010);
Record Record5 = new Record(110,"Record 5 Title","Author 5 Record",140,1987);
Record Record6 = new Record(160,"Record 6 Title","Author 1 Record",15,2010);
Record Record7 = new Record(107,"Record 7 Title","Author 1 Record",4,1980);
Record Record8 = new Record(1440,"Record 8 Title","Author 8 Record",1220,1970);
Record Record9 = new Record(1120,"Record 9 Title","Author 9 Record",1123,2010);
List<Record> Records = Arrays.asList(Record1,Record2,Record3,Record4,Record5,Record6,Record7,Record8,Record9);
//top 2 record of year 2010
int m = 2;
int year = 2010;
System.out.println(Arrays.toString(Records.stream().filter(s -> s.getYearPublished() == year).sorted((r1, r2) -> Integer.compare(r2.popularity, r1.popularity)).limit(m).toArray()));
//average top 2 record of Author 1 Record
String author= "Author 1 Record";
int n = 2;
System.out.println(Records.stream().filter(s -> author.equals(s.getAuthor())).sorted((r1, r2) -> Integer.compare(r2.popularity, r1.popularity)).limit(n).mapToInt(Record::getSales).average().getAsDouble());
This prints:
[Record 9 Title, Record 4 Title]
72.5
Having a collection of objects you can use stream api to collect/filter/reduce your results. There is not so much to it.
The main problem is to not load all of the objects to memory and to be able to retrieve them from whatever store efficiently by using indexes, reverse-indexes.
One of the frameworks which came to my mind is Apache spark
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.
I'm developing a custom Adsense report tool using Google Java Client Library for Android. I've successfully authenticated and can make API calls to the server. but now when I receive the response, I don't know how to parse it and correctly show the result to user.
According to the javaDocs, AdsenseReportsGenerateResponse.getRows() generates a List> But I'm kinda lost how to properly parse it to get:
-Today's earnings
-Yesterday's earnings
-Last 7 days
-Last month
-From the beginning of time
Here's part of my code related to the question
Reports.Generate request = adsense.reports().generate(startDate, endDate);
request.setMetric(Arrays.asList("PAGE_VIEWS", "AD_REQUESTS", "AD_REQUESTS_COVERAGE", "CLICKS",
"AD_REQUESTS_CTR", "COST_PER_CLICK", "AD_REQUESTS_RPM", "EARNINGS"));
request.setDimension(Arrays.asList("DATE", "WEEK", "MONTH"));
request.setSort(Arrays.asList("+DATE"));
AdsenseReportsGenerateResponse response = request.execute();
//TODO: Here be dragons
response.getRows();
Edit: Here is the javaDoc which mentions the getRow()
Hmm it seems nobody on this site can help?!
You should find our sample code useful: http://code.google.com/p/google-api-java-client/wiki/APIs#AdSense_Management_API
Namely, this is the file you're interested in: http://code.google.com/p/google-api-java-client/source/browse/adsense-cmdline-sample/src/main/java/com/google/api/services/samples/adsense/cmdline/GenerateReport.java?repo=samples
Here's a snippet of code to print the output. Mind you, this is for a command line application, but should be easily adaptable:
if ((response.getRows() != null) && !response.getRows().isEmpty()) {
// Display headers.
for (AdsenseReportsGenerateResponseHeaders header : response.getHeaders()) {
System.out.printf("%25s", header.getName());
}
System.out.println();
// Display results.
for (List<String> row : response.getRows()) {
for (String column : row) {
System.out.printf("%25s", column);
}
System.out.println();
}
System.out.println();
} else {
System.out.println("No rows returned.");
}
As for getting the data for different periods of time, you should probably be running different reports, not cramming it all into one, as that would take different start dates and end dates. Here's how it works:
Today's earnings: set the start and end dates to today, set the dimension list to just DATE
Yesterday's earnings: set the start and end date to yesterday, set the dimension list to just DATE
Last 7 days: if you want data per day, then you set the start date to 7 days ago, the end date to today, and the dimension list to just DATE. If you want to aggregate the stats, you may need to calculate this yourself, as WEEK and MONTH refer to a calendar week and month, not the last 7 days.
Last month: start date 1st of last month, end date last day of the month, dimension MONTH.
All time: how do you want this aggregated? Per month? Then set the start date to, say, 1980-1-1, end date to today and dimension to MONTH.
This blog post should help with understanding reporting concepts a bit better: http://adsenseapi.blogspot.com/2011/11/adsense-management-api-diving-into.html
Let me know if you need help with anything else!
Its not a List<List> as far as I understand the api. Try this:
String[][] array = response.getRows();
for (int i = 0; i < array.getSize(); i++){
String dimension = array[i][0];
String metric = array[i][1];
//Do what you want with them
}
I am writing this because the API says it has a list of dimensions with one value for the string and one for the metric, as far as I understand.
If you expect several cells on each row (Which I believe the API doesn't work that way), you need to add another for inside and get the size of the current list probably with something like array[i].getSize()
Post back if it doesn't help you.
Edit: I see now. Try this:
List list = response.getRows();
for (int i = 0; i < list.size(); i++){
List<String> list2 = list.get(i);
for (int j = 0; j < list2.size(); j++){
String value = list2.get(j);
//Do what you want
}
}