I have a description of a method, but I do not understand how to put it correctly.
/**
* Add an artist to Karaoke<br>
* Find the end of the artist arrangement and add the new artist to that position.<br>
*/
public void addArtist(String name, String category, String image) {
for (int i = 0; i < artistas.length; i++) {
artistas[i] = new Artista(name, category, image);
}
}
But I do not understand how to complete the route of the arrangement.
I appreciate your help in advance.
I think your updated working solution would look like this
public void addArtist(String name, String category, String image) {
artista = Arrays.copyOf(artista, artista.length + 1);
for (int i = 0; i < artistas.length; i++) {
artistas[i] = new Artista(name, category, image);
}
}
Hope this helps!
If you just need to find the first empty index at the end, it should be enough to check for null, because object arrays are initialized with null.
public void addArtist(String name, String category, String image) {
for (int i = 0; i < artistas.length; i++) {
if(artistas[i] == null) {
artistas[i] = new Artista(name, category, image);
break;
}
}
}
Beware: The above code will not work anymore, if there's a null value somewhere inbetween two Artista objects in the array. In that case the new Artista will be inserted into that index instead.
Related
I'm having trouble writing a for-each loop that searches the arraylist and returns the county's name within the continent that has the highest gdp. Here's my code for it right now. (ElementsList is the original ArrayList)
public Country highestGdp(String continent) {
boolean flag;
for (Country cont : ElementsList) {
if (cont.getContinent().equals(continent)) {
ArrayList<Country> TMP1 = new ArrayList<Country>();
TMP1.add(cont);
for (Country gdp : TMP1) {
double max = 0;
if (max < gdp.getGDP()) {
max = gdp.getGDP();
}
if (gdp.getGDP() == max) {
ArrayList<Country> TMP2 = new ArrayList<Country>();
TMP2.add(gdp);
}
return gdp;
}
}
}
return null;
}
Each time you find a country in the right continent, you can check to see if it is greater than the max so far. Don't need to loop through all of them each time.
public Country highestGdp(String continent) {
boolean flag;
Country maxCountry = null;
for (Country cont : ElementsList) {
if (cont.getContinent().equals(continent)) {
if (maxCountry == null) maxCountry = cont;
if (maxCountry.getGDP() < gdp.getGDP()) {
maxCountry = cont;
}
}
}
return maxCountry;
}
Sorry for saying it but Your code is a little messy ;)
To shortly solve Your problem, try to move max declaration before the loop like this:
[...]
double max = 0;
for(Country gdp : TMP1){
[...]
We can see that TMP2 is completely useless, remove it:
// ArrayList<Country> TMP2 = new ArrayList<Country>();
// TMP2.add(gdp);
You create TMP1 list always with only 1 element and then iterate over it. This is also useless, You can do the code directly on the element You are adding to the list.
First iteration over ElementList is a list of Country elements, but the element You iterate is called cont (=continent) which is a Continent and not the Country. Is it intended to use Country class to cover both: Countries and Continents? Do You plan to have a tree structure like "Continents contains many Countries"?
Final code to solve problem from Your original question should be like this:
public Country highestGdp(String continent){
Country countryWithMaxGdp = null;
for(Country cont: ElementsList ){
if(cont.getContinent().equals(continent)){
if(countryWithMaxGdp == null || countryWithMaxGdp.getGDP() < cont.getGDP()){
countryWithMaxGdp = cont;
}
}
}
return countryWithMaxGdp;
}
Ok this might seem easy but its been bugging my mind for days and I honestly don't know why it the index wont increase and get the other data. I dont know where to but the return. I placed it in 2 lines and the first one only gives the first row of data from the database and the second one only gives the last one from the database. (See commented out lines below). How to get each row that fits the if-statements?
Here's my code:
public Object[] populateTable(ArrayList<Outlet> outletList, String selection, int size, int monthCtr, String selDay){
for(int i = 0; i<outletList.size(); i++){
if(outletList.get(i).getCity().equalsIgnoreCase(selection)){
if(outletList.get(i).getStatus().equals("ACTIVE")){
bar = outletList.get(i).getBarangay();
code = Integer.toString(outletList.get(i).getCode());
name = outletList.get(i).getName();
data = new Object[]{bar, name, code};
//return data ->gives the first one in the database
}
}
}
}
//return data -> gives the last one in the database
}
You need to save all your results in another array and return that instead.
public Object[] populateTable(ArrayList<Outlet> outletList, String selection, int size, int monthCtr, String selDay)
{
List<object> result = new List<object>();
for(int i = 0; i<outletList.size(); i++)
{
if(outletList.get(i).getCity().equalsIgnoreCase(selection))
{
if(outletList.get(i).getStatus().equals("ACTIVE"))
{
bar = outletList.get(i).getBarangay();
code = Integer.toString(outletList.get(i).getCode());
name = outletList.get(i).getName();
data = new Object[]{bar, name, code};
result.Add(data);
}
}
}
return result.ToArray();
}
try this:
public List<Outlet> populateTable(ArrayList<Outlet> outletList, String selection, int size, int monthCtr, String selDay){
List<Outlet> data = new ArrayList<Outlet>();
for(int i = 0; i < outletList.size(); i++){
if(outletList.get(i).getCity().equalsIgnoreCase(selection) &&
outletList.get(i).getStatus().equals("ACTIVE")){
data.add(outletList.get(i));
}
}
return data;
}
Your problem here is as follow:
Your first return statement, will exit the for loop, and return
the first object, as your results have shown.
Your second return statement, will, as you have explained, only
return the last record that was iterated over in the for loop.
Your third problem is on this line data = new Object[]{bar, name,
code};. After every loop, you instantiate the data object to a new
array of objects, instead of adding the values to the array, so essentially, you are always creating an array of objects with 1 item in it, the last one that was iterated.
If you want to return all objects in the array, you should try the following:
public Object[] populateTable(ArrayList<Outlet> outletList, String selection, int size, int monthCtr, String selDay)
{
Object[] result = new Object[outletList.size()];
for (int i = 0; i < outletList.size(); i++)
{
if (outletList.get(i).getCity().equalsIgnoreCase(selection))
{
if (outletList.get(i).getStatus().equals("ACTIVE"))
{
bar = outletList.get(i).getBarangay();
code = Integer.toString(outletList.get(i).getCode());
name = outletList.get(i).getName();
var data = new { bar, name, code };
result[i] = data;
}
}
}
return result;
}
I really tried searching for the solution to this problem, but I cant seem to get it right. I have an application that Im working on, and I would like to print out all of a customers orders in a JTable with rows. So if a customer has three orders I want it to show each order on a separate row.
With this code (the next block) I got it to work, but it's only printing out the last value. So if I have Order 3 attached to a customer, and then add Order 4, it only shows Order 4.
JButton btnHämtaKund = new JButton("Hämta");
btnHämtaKund.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String searchTerm = sökrutaKund.getText();
Customer c = Controller.findCustomer(searchTerm);
String sum = "";
if (c != null) {
if (c.getOrders() != null) {
for (Order tmp : c.getOrders().values()) {
String date = tmp.getDate();
String price = Double.toString(tmp.getPrice());
String rfd = "";
if (tmp.getRdyForDelivery() == true) {
rfd = "Ready for delivery";
} else if (tmp.getRdyForDelivery() == false) {
rfd = "Processing";
}
model.addRow(new String[] {date, price, rfd});
}
txtfieldTestKund.setText(sum);
} else {
txtfieldTestKund.setText("c.getOrders() == null");
}
} else {
txtfieldTestKund.setText("c == null");
}
}
});
Model is my DefaultModelTable.
I also tried with a for-loop like this in case I was overwriting my last row all the time:
for (int i = 0; i < c.getOrders().size(); i++) {
String date = c.getOrders().get(i).getDate();
String price = Double.toString(c.getOrders().get(i).getPrice());
String rfd = "";
if (c.getOrders().get(i).getRdyForDelivery() == true) {
rfd = "Ready for delivery";
} else if (c.getOrders().get(i).getRdyForDelivery() == false) {
rfd = "Processing";
}
Object row[] = {date, price, rfd};
model.addRow(row);
}
but that just gave a Nullpointerexception.
Any ideas what to do? Really thankful for help!
I had to fix a method to increase the key for each Order i added to Customer, looks like I was overwriting the previous with the last one.
private int counter = 0;
public void add(Order o) {
counter += 1;
String newCounter = Integer.toString(counter);
this.orders.put(newCounter, o);
}
I'm making a media player currently, and I've been searching all day long how to make a new list view that displays all the artists in the phone.
the type of list where if you click onto it, itll go to a list of the albums by that artist, then the songs etc
the extent of what I know that I have to do is use MediaStore to sort it out, but Im just stumped.
Any help? I dont even have code to go off of, cause ive been trying and deleting what Ive been doing
I understand how it's like to have absolutely nothing to even know where to start looking.
Anyway, I use the following code for getting a list of Artists.
public ArrayList<ArtistItem> getArtistList() {
ArrayList<ArtistItem> artistList = new ArrayList<ArtistItem>();
Uri uri = MediaStore.Audio.Artists.EXTERNAL_CONTENT_URI;
String[] projection = new String[] {MediaStore.Audio.Artists._ID, MediaStore.Audio.ArtistColumns.ARTIST, MediaStore.Audio.ArtistColumns.NUMBER_OF_TRACKS};
Cursor musicCursor = getContentResolver().query(uri, projection, null, null, null);
int idColumn = musicCursor.getColumnIndex(MediaStore.Audio.Artists._ID);
int titleColumn = musicCursor.getColumnIndex(MediaStore.Audio.ArtistColumns.ARTIST);
int numColumn = musicCursor.getColumnIndex(MediaStore.Audio.ArtistColumns.NUMBER_OF_TRACKS);
// Iterate over the List
if(musicCursor!=null && musicCursor.moveToFirst()) {
//add songs to list
do {
String id = musicCursor.getString(idColumn);
String title = musicCursor.getString(titleColumn);
String num = musicCursor.getString(numColumn);
if(title == null || title.equals(MediaStore.UNKNOWN_STRING)) {
title = "Unknown Artist";
}
if(num.equals("1")) {
num = num + " Song";
} else {
num = num + " Songs";
}
artistList.add(new ArtistItem(thisId, thisTitle, thisNum));
} while (musicCursor.moveToNext());
}
return artistList;
}
public class ArtistItem{
private String id;
private String title;
private String num;
ArtistItem(String theId, String theTitle, String theNum) {
id = theId;
title = theTitle;
num = theNum;
}
// TODO Implement getters and setters for id, title and num
}
Can someone could be kind and help me out here. Thanks in advance...
My code below outputs the string as duplicates. I don't want to use Sets or ArrayList. I am using java.util.Random. I am trying to write a code that checks if string has already been randomly outputted and if it does, then it won't display. Where I am going wrong and how do I fix this.
public class Worldcountries
{
private static Random nums = new Random();
private static String[] countries =
{
"America", "Candada", "Chile", "Argentina"
};
public static int Dice()
{
return (generator.nums.nextInt(6) + 1);
}
public String randomCounties()
{
String aTemp = " ";
int numOfTimes = Dice();
int dup = 0;
for(int i=0 ; i<numOfTimes; i++)
{
// I think it's in the if statement where I am going wrong.
if (!countries[i].equals(countries[i]))
{
i = i + 1;
}
else
{
dup--;
}
// and maybe here
aTemp = aTemp + countries[nums.nextInt(countries.length)];
aTemp = aTemp + ",";
}
return aTemp;
}
}
So the output I am getting (randomly) is, "America, America, Chile" when it should be "America, Chile".
When do you expect this to be false?
countries[i].equals(countries[i])
Edit:
Here's a skeleton solution. I'll leave filling in the helper methods to you.
public String[] countries;
public boolean contains(String[] arr, String value) {
//return true if value is already in arr, false otherwise
}
public String chooseRandomCountry() {
//chooses a random country from countries
}
//...
int diceRoll = rollDice();
String[] selection = new String[diceRoll];
for ( int i = 0; i < selection.length; i++ ) {
while (true) {
String randomCountry = chooseRandomCountry();
if ( !contains(selection, randomCountry ) {
selection[i] = randomCountry;
break;
}
}
}
//...then build the string here
This doesn't check important things like the number of unique countries.
You need a data structure which allows you to answer the question "does it already contain item X?"
Try the collection API, for example. In your case, a good candidate is either HashSet() or LinkedHashSet() (the latter preserves the insert order).
You'd probably be better of using another structure where you save the strings you have printed. Since you don't want to use a set you could use an array instead. Something like
/*
...
*/
bool[] printed = new bool[countries.length];
for(int i=0 ; i<numOfTimes ; /*noop*/ )
{
int r = nums.nextInt(countries.length);
if (printed[r] == false)
{
i = i + 1;
printed[r] = true;
aTemp = aTemp + countries[r];
aTemp = aTemp + ",";
}
}
return aTemp;
Consider what you're comparing it to:
if (!countries[i].equals(countries[i]))
are you comparing c[i] to c[i]? or c[i] to c[i-1]? Or do you need to check the whole array for a particular string? Perhaps you need a list of countries that get output.
make list uniqueCountries
for each string called country in countries
if country is not in uniqueCountries
add country to uniqueCountries
print each country in uniqueCountries
When you do this, watch out for index out of bounds, and adjust accordingly
Much faster way to do it then using HashSets and other creepy stuff. Takes less code too:
public String randomCounties() {
List<String> results = Arrays.asList(countries);
Collections.shuffle(results);
int numOfTimes = Dice();
String result = " ";
for(int i=0 ; i<numOfTimes; i++) {
result = result + countries[i] + ", ";
}
return result;
}
If you want to avoid outputting duplicate values, you need to record what values have already been listed or remove values from the pool of possibilities when they get selected.
You mention that you do not want to use Sets or ArrayList (I assume you mean Lists in general), I assume that is a requirement of the assignment. If so, you can accomplish this by building arrays and copying data between them the same way that an ArrayList would.
one note, your current implementation chooses between 1 and 6 entries from and array of 4 entries. If you force the selections to be unique you need to decide how to handle the case when you have no more unique selections.