Copying the first two values of an array into a new array - java

I have sorted an array of objects into descending order based on one of their variables. I now need to take the first two values of this array and place them in a new String array. What I have so far is below, but Im obviously making a stupid mistake somewhere.
public String[] teamsToProgress()
{
Arrays.sort(teams);
String[] teamsToProgress = new String[2];
for (int i=0; i<2 ; i++)
{
teams[i] = teamsToProgress[i];
}
}

You try to assign String to a Team field (here: teams[i] = teamsToProgress[i];). You'll have to convert (not casting) the String to a Team instance before assigning.

If your just looking for a logical error, here it is:
teams[i] = teamsToProgress[i]; should be replaced to teamsToProgress[i] = teams[i];
I'm not getting into the details of the syntax involved. But I guess this is what you wanted based on your question.

teams[i] = teamsToProgress[i]; should be reversed, this make no sense. You're also missing a return statement.
public String[] teamsToProgress()
{
Arrays.sort(teams);
String[] teamsToProgress = new String[2];
for (int i=0; i<2 ; i++)
{
teamsToProgress[i] = teams[i]; //.getSomething() ?
}
return teamsToProgress;
}

your question is not clear enough as we still need to learn about Team object structure. but I'm guessing you are looking after something like this.
public String[] teamsToProgress(Team[] teams) //pass your sorted teams array as a param.
{
String[] teamsToProgress = new String[2];
for (int i=0; i<2; i++)
{
teamsToProgress[i] = String.valueOf(teams[i]); //convert teams[i] to string
}
return teamsToProgress;// you need to return an array
}

Related

How can i remove an element from array in Java

Hello everyone i am trying to remove an name that the user has put in from an String Array, i am new to programming and i have tried this but it doesn't work. Can someone help me or tell me what i am doing wrong?
String [] myName = {"Testname","Charel","melissa","Kelly"};
removeName(myName);
public void removeName(String[] names )
{
Scanner sc = new Scanner(System.in);
String name = "";
name = sc.nextLine();
for (int i = 0; i < names.length; i++) {
name = names[i-1];
}
}
How can i do this?
You probably need to use Lists for this. Your list will be a list of String, and use remove() method to do this.
An array's length is fixed and can't be changed this way.
Useful Link : Removing items from a list
First off, an array does not change size after it is initialized, the only way to change the size of an array is to replace it with a new array! So in order to not end up with a double entry or an empty field, you would need to make a new array that is one size shorter, and write the names you want to keep into that.
An array might be ill-suited for your purposes, so consider using a list or an ArrayList. A list can be resized, so removing an element will automatically shorten the list. I recommend you look into that.
Lastly, you currently aren't even comparing your input to your fields. Replace name = names[i-1]; with something along the lines of
if(name.equals(names[i]))
//TODO: Remove from list
See here for more details about String.equals()!
Also, keep in mind that the user input might not match any name at all, so prepare for that case as well!
To remove an element from an array in Java, you need to create a new array and copy over all the elements you want to keep. That is because Java arrays are fixed-size.
For example, to remove an element at a particular index, you could do it like this:
public static String[] remove(String[] array, int index) {
String[] result = new String[array.length - 1];
System.arraycopy(array, 0, result, 0, index);
System.arraycopy(array, index + 1, result, index, result.length - index);
return result;
}
You would then remove melissa from your array as follows:
String[] names = { "Testname", "Charel", "Melissa", "Kelly" };
names = remove(names, 2);
System.out.println(Arrays.toString(names));
Output
[Testname, Charel, Kelly]
Of course, it would be much easier to do it using a List:
List<String> names = new ArrayList<>(Arrays.asList("Testname", "Charel", "Melissa", "Kelly"));
names.remove(2);
System.out.println(names);
Or:
List<String> names = new ArrayList<>(Arrays.asList("Testname", "Charel", "Melissa", "Kelly"));
names.remove("Melissa");
System.out.println(names);
Output of both is the same as above.
There are some simple methods using java api provide by jdk, for example:
String [] myName = {"Testname","Charel","melissa","Kelly"};
List<String> container = new ArrayList(Arrays.asList(myName));
container.remove("Charel");
String[] result = new String[myName.length - 1];
container.toArray(result);
Alternatively you can also use this to convert array to list,
Collections.addAll(container, myName);
String [] myName = {"Testname","Charel","melissa","Kelly"};
removeName(myName);
public void removeName(String[] names )
{
Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
for (int i = 0; i < names.length; i++) {
if(names[i]==name)
{
for(int j=i;j<names.length-1;j++)
{
names[j]=names[j+1];
}
}
}
}

Dynamically initialise array name

I am trying to create an array of objects with a MAX_N 6 object into this array, then create another array within an else statement to fit the rest of the array objects.
I would like to name the new array
sbag1
sbag2
etc
here is my code:
public static ShoppingBag[] packIntoBags(GroceryItem[] goods) {
ShoppingBag newBag = new ShoppingBag();
GroceryItem tmpObject = null;
int index = 0;
String bag = "newBag";
String bagNum = bag + index;
for (int i = 0; i < MAXNBAG; i++)
if (newBag.numItems() < MAX_NUM_ITEMS) {
for (int k = 0; i < MAX_NUM_ITEMS; i++) {
tmpObject = goods[i];
newBag.addToBag(tmpObject);
}
}
else {
ShoppingBag newBag1 = new ShoppingBag();
}
}
You will not be able to dynamically create new variables in java.
When I look at the signature of your method you don't need to return multiple variables, only an array of ShoppingBags.
You should create a variable of type List<ShoppingBag>:
List<ShoppingBag> shoppingsBags=new ArrayList<>();
each time you need a new ShoppingBag:
bag=new ShoppingBag();
shoppingBags.add(bag);
at the end convert this list to an array:
return shoppingBags.toArray(new ShoppingBag[0]);
Java is a statically compiled language. In general, it is not possible, or to be precise: not helpful to use "dynamic" names for variables.
What you could do instead: use a Map, or even more simple: an array of arrays to hold your data.

Java - How to get the index of a given element in an array

I have an array of contacts like so :
public class Application {
private Scanner input;
private Contact[] contacts;
private int ArrayNum;
public Application() {
input = new Scanner(System.in);
contacts = new Contact[5];
ArrayNum = 0;
}
And what I want to do is enter a name of someone on the contacts list and if they are found on their list return their index like so:
System.out.println("Who do you want to remove?");
String name = input.nextLine();
for(Contact c: contacts){
if(c.getName().equals(name)){
//Get the index here
}
}
I tried researching this but no answer or guide seems to be very clear on this so I'm hoping that someone can explain this for me.
Thank you for looking
for(int index = 0; index < contacts.length; index++) {
if(contacts[index].getName().equals(name)) {
// use the index here
}
}
I don't think this code snippet needs any further explanation.
Use a for loop that uses a counter instead.
for(int i = 0; i < contacts.length, i++) {
if(contacts[i].getName().equals(name)) {
// do something with the index, i
}
}
You could use a counter
System.out.println("Who do you want to remove?");
String name = input.nextLine();
int remove_index = -1;
for(int i=0; i<contacts.length; i++){
Contact c = contacts[i];
if(c.getName().equals(name)){
remove_index =i;
}
}
Another alternative that may be helpful down the line is to use an ArrayList<Contact> instead of a c-style array (Contact[]). This class might add more handling complexity than it's worth, but it includes a lot of useful extra methods, including an int indexOf(<T> object) where <T> is the type you specified in your declaration (i.e., Contact for ArrayList<Contact> contacts).
Bad idea! You can't do that seriously, if you have an array. Of course you can set an index to null, but then you have to search for a null entry to reference a new contact within the array.
Note: you have an Iterator while writing
for(Contact c: contacts){...
So one option is to iterate by index, but it's a bad option. Better make your Array a Set. Then you might write:
for (Iterator<Contact> iter = mySet.iterator();iter.hasNext();) {
final Contact next = iter.next();
if(next.getName() == "NAME") {
iter.remove();
break;
}
Always use Iterator.remove()! Otherwise you will get Exceptions earlier than you wish :D

Split into separate arrarys

All the split command I have seen split (for example) a CSV file into the 1 array.
e.g.
cat,feline,house
dog,canine,house
monkey,primate,zoo
Into
array[0] = cat
array[1] = feline
array[2] = house
Is there a way to split them into separate arrays per line so it would be more like (so you can keep specific attributes in the same lines of the csv:
into
animal[0] = cat
species[0] = feline
lives[0] = house
A much better approach is to create a POJO:
public class MyAnimal {
private String animal;
private String family;
private String place;
private String country;
// getters and setters...
}
Then you can use a parser or read the file line by line and convert it to a List<MyAnimal>
Using array to hold object data is not the way to do it.
You can try this
BufferedReader br = new BufferedReader(new FileReader("D:\\sample.txt"));
String st = null;
String[] animal = new String[10];
String[] species = new String[10];
String[] lives = new String[10];
int j = 0;
while ((st = br.readLine()) != null) {
String[] str = st.split(",");
for (int i = 0; i < str.length; i++) {
animal[j] = str[0];
species[j] = str[1];
lives[j] = str[2];
}
j++;
}
But it is better to use ArrayList here.
Such an abstract split does not exist as a default as far as I know.
The basic way you would go about achieving this, would be first to do the regular split as you said, which gave the result.
array[0] = cat
array[1] = feline
array[2] = house
Then you could loop through the array and check for the different things.
ArrayList<String> animals = new ArrayList<String>();
ArrayList<String> lives = new ArrayList<String>();
for (int i = 0; i < array.length; i++) {
if (array[i].equalsIgnoreCase("cat") || array[i].equalsIgnoreCase("dog")) {
animals.add(array[i]);
}
else if (array[i].equalsIgnoreCase("house") || array[i].equalsIgnoreCase("zoo")) {
lives.add(array[i]);
}
}
Then you would of course do that for all the cases you have. It's a pretty complex way to do it, though really simple to understand.
Edit
To achive what you asked in the comments, you could do something like this.
ArrayList<String> animals = new ArrayList<String>();
ArrayList<String> lives = new ArrayList<String>();
for (int i = 0; i < array.length; i += 5) {
animals.add(array[i]);
lives.add(array[i + 1]);
}
Then the + 1 for selecting the index in the array would of course depend on the index from the splitted String.
String.split works like separating items by the delimiters, it doesn't know what a item is. If you want to associate items on some pattern to be recognized when parsing the string, you should supply those patterns to the categories the items should be associated to. If it's a CSV and you want to get the table data, then you should supply the metadata described the column names and dimensions. Without this metadata it's impossible to parse your document correctly.

Add string paramater to end of array

I have to add a String parameter to the end of an array. And throw an exception if the String already exists in the array. I don't know. Can anyone help?
This is what I have so far
public static void addCity (String city) throws Exception
{
for (int i = 0; i < MAX_CITIES;i++)
{
if (city == cityNames[i])
throw new Exception("This city already exists");
}
String [] temp = new String[cityNames.length+1];
for (int i = 0; i < cityNames.length;i++) {
temp[i] = cityNames[i];
}
temp[temp.length-1] = city;
cityNames = temp;
manyItems++;
}
To test if String a equals String b, use a.equals(b), not a == b.
(a == b works in C++, not Java.)
Your code looks fine except for the String comparison:
if (city == cityNames[i])
This won't do a proper String comparison: it will only compare the object references, which will usually be false.
Use String.equals for this:
if (city.equals(cityNames[i]))
It'd be easier to use a List:
List<String> cityNames = new ArrayList<String>();
if(cityNames.contains(city)) {
throw new Exception("This city already exists");
}
cityNames.add(city);
What is MAX_CITIES? I think your first loop should be until i < cityNames.length, not MAX_CITIES, since you don't seem to be updating MAX_CITIES when you increase the size of the array.
You should be using the equals() method to compare String objects, rather than ==.
It also might be nice if instead of just making the new array one element bigger, you double the size. That way you don't have to go through all the work of copying the array every time you add a new element. You'd need a variable to keep track of the next empty spot in the array, and it would look something like this:
if (nextEmptyIndex == cityNames.length)
{
String [] temp = new String[cityNames.length*2];
for (int i = 0; i < cityNames.length;i++) {
temp[i] = cityNames[i];
}
}
temp[nextEmptyIndex] = city;
nextEmptyIndex++;
manyItems++;

Categories

Resources