Filling an array with objects - java

I need some help with a homework question I am working on.
I need to create a "Library" class that contains an array of Song objects.(capacity of 10).
Then make a method addSong.
Here's what I have so far:
public class Library{
Song[] arr = new Song[10];
public void addSong(Song s){
for(int i=0; i<10; i++)
arr[i] = s;
}
}
My question is: Is there another way to fill the array? i will later need to search for a song based on a index value. So i will create a method like:
public Song getSong(int idx)
Thank you in anticipation for your answers!

If you really have to use an array (and not an ArrayList or LinkedList), this solution may be the right for you:
public class Library{
private Song[] arr = new Song[10];
private int songNumber = 0; //the number of Songs already stored in your array
public void addSong(Song s){
arr[songNumber++] = s;
}
}
If you want to avoid a runtime-exeption if you add more then 10 songs:
public void addSong(Song s){
if(songNumber<10)
{
arr[songNumber++] = s;
}else{
//what to do if more then 10 songs are added
}
}

There are a number of ways of accomplish this.
The logic you're using is more or less ok.
But what you are doing here:
public void addSong(Song s){
for(int i=0; i<10; i++)
arr[i] = s;
}
Is filling all the Songs array with the same song, perhaps this would be better:
public void addSong(Song s, int index){
arr[index] = s;
}
Of course, if you pass a negative index, or an index greater than 9, you are gonna be in trouble.

Use an ArrayList instead of an array. This way you can use the ArrayList.add() function to append to the end of your array and the ArrayList.get(int index) function to get the array entry at index index.
public class Library{
ArrayList<Song> arr = new ArrayList<Song>();
public void addSong(Song s){
arr.add(s);
}
public Song getSong(int index){
return arr.get(index);
}
}

To expand on Vacation9s' answer:
ArrayList<Song> songArray = new ArrayList<Song>();
public void addSong(Song s){
songArray.add(s);
}

Related

Inserting into a simple Array and Deleting

public class DataOperations {
int arraySize=50;
int[]array=new int[arraySize];
public void generateRandomArray(){
for(int i=0;i<arraySize;i++){
array[i]=i;
}
}
public int getValueAtIndex(int index){
if(index<arraySize){
System.out.println("Your value At index "+index+" is "+array[index]);
return array[index];
}else{
System.out.println("Please Return an Index that is inbounds");
return 0;
}
}
public boolean doesArrayContainValue(int searchValue){
boolean valueInArray=false;
for(int i=0;i<arraySize;i++){
if(array[i]==searchValue){
valueInArray=true;
}
}
return valueInArray;
}
public void deleteIndex(int index){
if(index<arraySize){
for(int i=index;i<(arraySize-1);i++){
array[i]=array[i+1];
}
}
System.out.println(arraySize);
arraySize--;
System.out.println(arraySize);
}
public void printArray(){
for(int i=0;i<arraySize;i++){
System.out.print(i+"-");
System.out.println(array[i]);
}
}
public void insertValue(int index){
if(index<arraySize){
array[arraySize]=index;
System.out.println(arraySize);
arraySize++;
System.out.println(arraySize);
}
}
public void linearSearchForValue(int value){
boolean valueInArray=false;
System.out.println("The was Found and is at Index:");
for(int i=0;i<arraySize;i++){
if(array[i]==value){
System.out.println(i);
}
}
}
}
Hey So I created simple add and delete methods to my array. However, I am unsure about a couple parts. I Understand the add method, and that we are decreasing the arraySize from 50 to 49 for this specific array object that I created in my Driver class below. However, I am not sure why I cannot do my add method before my delete method insertValue method if I put arraySize++ before array[arraySize]=index, and did not call my deleteIndex method shouldnt my arraySize=51? but this throws an out of bounds exception
Driver Class Below
public class Driver {
public static void main(String[] args) {
DataOperations array=new DataOperations();
array.generateRandomArray();
array.insertValue(20);
array.printArray();
}
}
int arraySize=50;
You create an array of size 50. Arrays are of fixed size hence you cannot get an array of size 51. In your code, when adding/deleting an element from the array, you arent changing the size of the array. You are just moving the index to get your desired output. If you want a bigger array you can:
Create a new array of required size and copy all elements from old to new
Use ArrayList instead of arrays.

Passing arrays to a method

I'm fairly new to Java so please have some patience with me.
I was wondering how I could go about passing an array with a bunch of strings into a new method that would ask the user a question and then print the array. I then also want the input from the user to be stored in a different array but I feel confident I can do this part myself.
A fragment of what I think the code should look like is as follows:
public static void birdarray()
{
String[] birds = {"Blue Tit", "Blackbrid", "Robin"};
}
public static void wanttogetarrayinhere ()
{
String question = print("What bird are you reporting?");
print(birds);
I would appreciate a nudge in the right direction.
Just add it as a parameter:
public static void wanttogetarrayinhere(String[] arr)
{
String question = print("What bird are you reporting?");
print(arr);
}
Then pass in the desired array when you call it:
String[] birds = {"Blue Tit", "Blackbrid", "Robin"};
wanttogetarrayinhere(birds);
As was pointed out in the comments you'll also need an overloaded print() method, with an overload for a String parameter and one for a String[] parameter, e.g.:
public static void print(String str) {
System.out.println(str);
}
public static void print(String[] arr) {
StringBuilder builder = new StringBuilder();
for (int i=0; i<arr.length; i++) {
builder.append(arr[i]);
if (i<arr.length-1)
builder.append(", ");
}
System.out.println(builder.toString());
}
You could do this to get the array into the method:
public static void wanttogetarrayinhere(String[] input){
// then to print array out something like:
for (int i=0; i<input.length; i++){
System.out.println(input[i]);
}
}

Method for modifying an element in an Array list?

A friend of mine asked me to give him an example of how to create an array list as well as add, display, delete, and modify it I've already made methods for everything except modify so some help?
public class Manager {
private static ArrayList<String> list = new ArrayList<String>();
private static BPScanner kb = new BPScanner();
private static String name;
public static void main(String[] args) {
while (true) {
String input = kb.getMenuStringFromUser("List Manager","Add", "Delete", "Modify",
"Display", "Quit");
if (input.equals("Quit"))
break;
if (input.equals("Add")) {
add();
} else if (input.equals("Display")) {
display();
}else if(input.equals("Delete")){
delete();
}
}
}
public static void add() {
do{
name= kb.getStringFromUser("Enter name: ");
}while(!isAlpha(name));
list.add(name);
}
private static boolean isAlpha(String name){
char c;
for(int i=0; i<name.length(); i++){
c=name.charAt(i);
if('A'<=c&&c<='Z'||'a'<=c&&c<='z'||c==' '){
}else{
return false;
}
}
return true;
}
public static void display() {
System.out.println("\nList:");
for (int i=0; i < list.size(); i++) {
kb.getStringFromUser(list.get(i));
//System.out.println(name);
}
String input = kb.getStringFromUser("\nContinue (y/n)? ");
if (input.startsWith("n")) System.exit(0);
}
public static void delete(){
list.remove(name);
}
public static void modify(){
}
}
I literally have no idea of what to write to get it to modify the names put into the array, so any ideas?
Lets define the modify function as
public static void modify(String toModify, String modifyAs) {
int pos = ar.indexOf(toModify);
ar.set(pos, modifyAs);
}
toModify is Variable holds the item to modify and modifyAs holds the new item to add
Simply just pass an index parameter. Than you use that index to modify the element which is on position index. In order to change a certain value in the list you can use the list.set(index, element); (in your case the element is string) function.
public static void modify(int index)
{
string nextName = kb.getStringFromUser("Enter name: ");
list.set(index, nextName);
}
Below code shows you how to add, view and delete an element from a particular location in arraylist.
import java.util.ArrayList;
public class RemoveElementFromArrayListExample {
public static void main(String[] args) {
//create an ArrayList object
ArrayList arrayList = new ArrayList();
//Add elements to Arraylist
arrayList.add("1");
arrayList.add("2");
arrayList.add("3");
/*
To remove an element from the specified index of ArrayList use
Object remove(int index) method.
It returns the element that was removed from the ArrayList.
*/
Object obj = arrayList.remove(1);
System.out.println(obj + " is removed from ArrayList");
System.out.println("ArrayList contains...");
//display elements of ArrayList
for(int index=0; index < arrayList.size(); index++)
System.out.println(arrayList.get(index));
}
}
From java docs you can use ,
Replaces the element at the specified position in this list with the specified element (optional operation).
Parameters:
index - index of the element to replace
element - element to be stored at the specified position
list.set(your_index,element);
public static void modify() {
String origName = kb.getStringFromUser("Which name do you want to modify: ");
if (list.contains(origName)) {
int index = list.indexOf(name);
name = kb.getStringFromUser("Enter new name: ");
list.set(index, name);
}
}

storing command line args in an array class

Musical Chairs. Musical Chairs is a children’s game where the players walk around a group of chairs while some music is playing. When the music stops, everyone must sit down. But, there is one less chair than there are people, so someone gets left out. And, indeed, that person is out of the game. A chair is removed. And the game is played again; someone else goes out. This continues until there is only one player left, the winner.
I am having problems storing the command line arguments in the player[]
here is my code
import java.util.*;
public class MusicalChairs {
Player [] players;
Random r = new Random();
public static void main(String[] args){
MusicalChairs mc = new MusicalChairs();
mc.setUpGame(args);
}
public void setUpGame(String [] p){
System.out.println("This is how we stand.......");
for (int i = 0; i < p.length; i++){
System.out.println(p[i]+" is "+ Player.Status.IN);
}
}
public void showStatus(){
}
public void winner(){
System.out.println("is the winner");
}
}
class Player{
enum Status{IN,OUT};
private String name;
private Status status;
public Player(String n){
name=n;
}
public String getName(){
return name;
}
public void setStatus(Status s){
status=s;
}
public Status getStatus(){
return status;
}
public String toString(){
String ret = name;
if(status==Status.IN){
ret="IN ";
}
else{
ret="OUT ";
}
return ret;
}
}
You're not storing the arguments in your array. If your question is how to do it, then you should:
Initialize the players array.
For each argument, you must create a Player object and store it in the array.
Use the data in your program.
This could be done like this:
public void setUpGame(String [] p) {
System.out.println("This is how we stand.......");
//Initialize the `players` array.
players = new Player[p.length];
for (int i = 0; i < p.length; i++){
System.out.println(p[i]+" is "+ Player.Status.IN);
//For each argument, you must create a `Player` object and store it in the array.
players[i] = new Player(p[i]);
players[i].setStatus(Status.IN);
}
//Once your array is filled, use the data in your program.
//...
}
The question is still open: What's your specific problem?
I think you need to update your code to create new players and maintain the reference in your array...
public void setUpGame(String [] p){
System.out.println("This is how we stand.......");
// You may want to check for a 0 number of players...
players = new Player[p.length];
for (int i = 0; i < p.length; i++){
players[i] = new Player(p[i]);
players[i].setStatus(Player.Status.IN);
System.out.println(players[i].getName()+" is "+ players[i].getStatus());
}
}

How to access an array index of an Object instance

Good day!
I am wondering How can I access an array index of an Object instance.
My code is as follows:
public class PokerPlayer {
private String name = null;
private Card [] cardsOnHand = new Card[5];
//getter and setter
}
What i want is to access the cardsOnHandArray[index] so that i can call it on another class and set the values per index...
public class PokerGame {
public static void main (String [] Args){
PokerPlayer players []= new PokerPlayer[4];
for(PokerPlayer player : players){
for(int i =0; i<5; i++){
//ACCESS cardsOnHand index i and store something on it...
}
}
}
}
Any advice would be highly appreciated. How can i also improve my OO design? Thank you in advance
public class PokerPlayer {
...
public Card getCard(int index) {
return this.cardsOnHand[index];
}
public void setCard(int index, Card card) {
this.cardsOnHand[index] = card;
}
...
}
then use:
player.getCard(i);
player.setCard(i,new Card());
You almost have it. Just call this inside your inner loop:
cardsOnHand[i] = new Card();
Of course, change what is being assigned to the array according to your requirements.
you can do as:
for(PokerPlayer player : players){
for(int i =0; i<5; i++){
Card[] cards= player[i].getCardsOnHand();
cards[i] = new Card();
}
}
This should work:
public class PokerGame {
public static void main (String [] Args){
PokerPlayer players []= new PokerPlayer[4];
for(PokerPlayer player : players){
for(int i =0; i<5; i++){
Card card = player.cardsOnHand[i];
}
}
}
}
Since your cardsOnHand array is private, you have to use your (unprovided) setter function.
Which could be something like
public void setCard(int index, Card value){
cardsOnHand[index] = value;
}
And in used in your loop as
player.setCard(i, something)
Assuming that your PokerPlayer has a getter for the cardsOnHand array:
public class PokerGame {
public static void main (String [] Args){
PokerPlayer players []= new PokerPlayer[4];
for(PokerPlayer player : players){
for(int i =0; i<5; i++){
player.getCardsOnHand()[i] = new Card();
}
}
}
}
However, I think that a better solution is to add a method
public void setCard(Card card, int index) {
assert index < 5;
cardOnHands[index] = card
}
to your PokerPlayer.

Categories