Method for modifying an element in an Array list? - java

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);
}
}

Related

finding all possible permutations of a given ArrayList<String>, and Storing them in global variable

In the code given below I am adding the a particular permutation of ArrayList in the function permute but while printing in the main function all possible permutations are not printed. Instead, the same ArrayList<String> is printed n! times where n is length of given ArrayList<String>.
I am adding the permutations in set(my global variable) in permute function as set.add(names) but while printing it in main function it gives output as the same unarranged Arraylist.
import java.util.*;
public class Q1 {
static Set<ArrayList<String>> set = new HashSet<>(); ;
public static void main(String args[]) {
int n;
Scanner in = new Scanner(System.in);
n = in.nextInt();
ArrayList<String> names = new ArrayList<String>();
for(int i=0;i<n;i++) {
String temp;
temp = in.next();
names.add(temp);
}
System.out.println(set.size());
permute(names,0,names.size()-1);
System.out.println(set.size());
for(ArrayList<String> i : set) {
System.out.println(i);
}
}
public static void permute(ArrayList<String> names , int l, int r) {
if(l==r) {
if(set.contains(names)) {
return;
}
set.add((ArrayList<String>)names);
//System.out.println(names);
return;
}
for(int i=l;i<=r;i++) {
Collections.swap(names,l ,i);
permute(names , l+1, r);
Collections.swap(names,l,i);
}
}
}
You are repeatedly adding the same object names to set. But you need to add a copy of names.
set.add((ArrayList<String>)names);
→
set.add(new ArrayList<>(names));

How to replace or remove an object to non-null value in an array

I am building a classical Nim game for practicing. This project only uses an array to deal with the player data object. For removing the existing player, I created a method called removeplayer and assign the specific object to a null value.
So far, I am able to:
Create a non-null array for saving players' data that I can add (assign) new players.
During the test, the null value will be assigned a non-null value in the array. For example, I have an array length for 5 space, but only 2 players' data being put in the array. The rest of the place will be filtered with a non-null object.
I thought I could just assign the object I wanted to remove by assigning it to null, and when returning the array, it should be filtered with non-null object. However, it turned out to be malfunction that I can't remove the player data.
Therefore, is there any way to replace the existing data with a non-null object or any way to remove the object in the array?
Here is part of my code Nimsys:
public static void searchAndRemovePlayer(String user) {
for (int i = 0; i < NimPlayer.getCounter(); i++) {
String userName = NimPlayer.getPlayer()[i].getUserName().trim();
if (userName.equals(user)) {
NimPlayer.getPlayer()[i] = null;
System.out.println("Remove successfully!");// A test to see if the code runs
return;
}
}
System.out.println("The player does not exist.\n");
}
public static void main(String[] args) {
System.out.println("Welcome to Nim\n");
Scanner in = new Scanner(System.in);
while (true) {
System.out.print('$');
String commandin = in.next();
if (commandin.equals("removeplayer")) {
String user = in.nextLine().trim();
if (user.equals("")) {
System.out.println("Are you sure you want to remove all players? (y/n) \n");
commandin = in.next();
if (commandin.equals("y")) {
for (int i = 0; i < NimPlayer.getCounter(); i++) {
NimPlayer.getPlayer()[i] = null;
}
System.out.println("Remove all the players");
}
}
if (!user.equals("")) {
searchAndRemovePlayer(user);
}
}
}
And below is the part of the NimPlayer:
public class NimPlayer {
private String userName;
private String familyName;
private String givenName;
private int score;
private int gamePlayed;
private static int counter;
private static final int SIZE = 5;
static NimPlayer[] playerList = new NimPlayer[SIZE]; // set an array here
//define NimPlayer data type
public NimPlayer(String userName, String surName, String givenName) {
this.userName = userName;
this.familyName = surName;
this.givenName = givenName;
}
// create new data using NimPlayer data type
public static void createPlayer(String userName, String familyName, String givenName) {
if (counter<SIZE) {
playerList[counter++] = new NimPlayer(userName, familyName, givenName);
} else {
System.out.println("Cannot add more players.");
}
}
public static int getCounter() {
return counter;
}
public static NimPlayer [] getPlayer() {
NimPlayer[] nimPlayers = Arrays.stream(playerList).filter(Objects::nonNull).toArray(NimPlayer[]::new);
counter = nimPlayers.length; //update the counter
return nimPlayers; }
//getters and setters
}
What you are doing in NimSys is getting the player list array from NimPlayer, and then setting it to null in NimSys. It still exists in NimPlayer, so the next time you call getPlayer() it'll still return the complete array with no null values, as it was never modified in NimPlayer. What you should do instead is this:
in NimPlayer
create a new method called setPlayerList that takes array as a parameter. Then set the playerList in NimPlayer equal to this new array.
And in NimSys, create a new array and set it to getPlayerList, then set the value you want to null. Then call setPlayer() and parse the new array as parameter so that it will be modified in NimPlayer.
Based on #Ghost's statement, I figured out myself for doing this.
First in NimPlayer, create a setter for the playerList array. If the original array is static, then, the setter should be static as well.
public static void setPlayerList(NimPlayer [] newplayerList) {
NimPlayer.playerList = newplayerList; }
Second, to use the setter, I need to get the original array for replacing. And pick the element that I want to delete.
Third, call the setter to put the new array to replace the previous one.
NimPlayer [] playerList = NimPlayer.getPlayer();
for (int i = 0; i < playerList.length; i++) {
String userName =playerList[i].getUserName().trim();
if (userName.equals(user)) {
playerList[i] = null;
System.out.println("Remove successfully!");
NimPlayer.setPlayerList(playerList);//call the setter to replace older list
return;
}
}
Finally, wrap these lines of codes to a function in Nimsys.
public static void searchAndRemovePlayer(String user) {
NimPlayer [] playerList = NimPlayer.getPlayer();
for (int i = 0; i < playerList.length; i++) {
String userName =playerList[i].getUserName().trim();
if (userName.equals(user)) {
playerList[i] = null;
System.out.println("Remove successfully!");
NimPlayer.setPlayerList(playerList);
return;
}
}
System.out.println("The player does not exist.\n");
}

Phonebook Alphabetical Sorting according to the field First Name

I am trying to get my JavaFx application of a phone book in order to sort alphabetically the contacts list according to the first name. However, the existing loop is not listing the names in the correct order. Here is the sorting method:
public static void sortContactList() {
try {
for (int i = 0; i < contactList.length - 1; i++) {
for (int j = i + 1; i < contactList.length; j++) {
if ((contactList[j].first.toCharArray()[0]) < (contactList[i].first.toCharArray()[0])) {
Entry tmp = contactList[j];
contactList[j] = contactList[i];
contactList[i] = tmp;
}
}
}
} catch (NullPointerException exc) {}
}
Below it is shown how the contact list is made up. It is stored in a file with first being the person's first names as strings:
class Entry {
public String first, last, number, note;
}
public class Phonebookfor1510 {
public static Entry[] contactList;
public static int num_entries;
public static void main(String args[]) throws Exception {
int i;
char C;
String code, Command;
contactList = new Entry[200];
num_entries = 0;
The rest of my code works with it. I am just wondering why it is not sorting the list of values alphabetically. Any help would be greatly appreciated!!
I think the second for loop will never end without a NullPointerException. You are increasing j, but checking for i<contactList.
You could use Arrays.sort() in this case.
The Best thing You can Do is Use TreeSet. Like the given example
TreeSet<String> stringSet = new TreeSet<>();
stringSet.add("Mummy");
stringSet.add("Mahima");
stringSet.add("Gaurav");
stringSet.add("Naresh");
stringSet.add("Bhawna");
for(String s : stringSet) {
System.out.println(s);
}
Output :
Bhawna
Gaurav
Mahima
Mummy
Naresh
take a look at this sample code:
public class Entry implements Comparable<Entry>{
private Long id;
private String fullName;
private String phoneNumber;
public int compareTo(Entry other) {
if(other==null) throw new NullPointerException();
/*
-1 : phonenumber of current entry is smaller that other
0 : phonenumber of current entry is equal to other
+1 : phonenumber of current entry is greater than other
*/
return (this.getFullName().compareTo(other.getPhoneNumber()));
}
public static void main(String[] args){
Entry[] entriesArray = getEntriesArrayListFromSomewhere();
Arrays.sort(entriesArray);
}
//getters ans setters
}

Java - Need help to solve a bug

I am currently learning Java and for my inner classes practice, I played aroud the following code:
public class DataStructure {
// Create an array
private final static int SIZE = 15;
private int[] arrayOfInts = new int[SIZE];
public DataStructure() {
// fill the array with ascending integer values
for (int i = 0; i < SIZE; i++) {
arrayOfInts[i] = i;
}
}
public void printEven() {
// Print out values of even indices of the array
DataStructureIterator iterator = this.new EvenIterator();
while (iterator.hasNext()) {
System.out.print(iterator.next() + " ");
}
System.out.println();
}
interface DataStructureIterator extends java.util.Iterator<Integer> { }
// Inner class implements the DataStructureIterator interface,
// which extends the Iterator<Integer> interface
private class EvenIterator implements DataStructureIterator {
// Start stepping through the array from the beginning
private int nextIndex = 0;
public boolean hasNext() {
// Check if the current element is the last in the array
return (nextIndex <= SIZE - 1);
}
public Integer next() {
// Record a value of an even index of the array
Integer retValue = Integer.valueOf(arrayOfInts[nextIndex]);
// Get the next even element
nextIndex += 2;
return retValue;
}
public void setNextIndex(int i){
nextIndex=i;
}
}
public void print(DataStructureIterator iterator) {
// Print out values of odd indices of the array
//iterator = this.new EvenIterator();
iterator.setNextIndex(1);//**This line giving me compiler error that setNextIndex is undefined for type DataStructure.DataStructureIterator **
while (iterator.hasNext()) {
System.out.print(iterator.next() + " ");
}
System.out.println();
}
public EvenIterator createNewObject(){
return this.new EvenIterator();
}
public static void main(String s[]) {
// Fill the array with integer values and print out only
// values of even indices
DataStructure ds = new DataStructure();
System.out.println("Even Index");
ds.printEven();
System.out.println("Odd Index");
ds.print(ds.createNewObject());
}
}
I am passing a EvenIterator object to the method print(DataStructureIterator), as far as I know a iterator can refer to a EvenIterator object(since DataStructureIterator is a implemented by EvenIterator), though hasNext() and setNextIndex(int) are in the same class the reference iterator is able to access only hasNext.
How can I fix this bug?
Even though you are passing EvenIterator to the method print(DataStructureIterator), it is silently getting casted into DataStructureIterator. So if the setNextIndex(int) method is not declared in DataStructureIterator, you will not be able to access it.
The print method know its parameter is a DataStructureIterator. Is the method setNextIndex declared in that interface? If not, you must add it.

Return ArrayList from ArrayList method type

I'm making a little card deck program that uses an ArrayList for the deck. One of the limitations set upon me is that the method in which I "deal" the cards must be an Arraylist type. The problem I'm running into is that I don't know how to return just a specific index value from the ArrayList. See below.
public ArrayList deal(int n, boolean up){
Card card0 = new Card();
boolean cardFace = card0.state(up);
return al.get(0); //<-- This doesn't work, Netbeans says that it is a string type
//not an ArrayList type. The only thing it will actually
//allow me to return is:
return.al; // But this doesn't work, I don't need to return the whole list,
// just the first element, but Netbeans calls that a String type, not
// ArrayList
So how can I return the first item of the List and still have it be the correct type? The rest of the code doesn't matter, just the Method type and return statement.
EDIT: As requested
package deckofcards;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Deck{
ArrayList<String> al = new ArrayList<>();
public void shuffle(){
Collections.shuffle(al);
}
public String displayDeck(){
String returnDeck = "";
for(int i = 0; i < al.size(); i++){
String printDeck = al.get(i);
returnDeck += printDeck;
}
return returnDeck;
}
public ArrayList deal(int n, boolean up){
Card card0 = new Card();
boolean cardFace = card0.state(up);
return al.get(0);
}
public void populate(){
al.add(0, "Ace of Spades");
al.add(1, "Two of Spades");
al.add(2, "Three of Spades");
//yadaa yadaa
If you cannot change the signature and it is mandatory to return an arraylist, then you can create an arraylist with just one element and return it. Something like this:
ArrayList returnList = new ArrayList();
returnList.add(al.get(0));
return returnList;
Does not look great to me :-(
In your specific case, al is an ArrayList<String>. That means al.get(...) returns a String. However, your method is declared as returning an ArrayList, which is not a String. You will either need to change your method return type to String, or you will need to construct a new ArrayList and add your single string to it and return that.
Your declared return type needs to match the object you are returning. So for example:
ArrayList<String> al = ...;
String getSingleItem (int index) {
return al.get(index);
}
ArrayList<String> getSingleItemAsArrayList (int index) {
ArrayList<String> single = new ArrayList<String>();
single.add(al.get(index));
return single;
}
ArrayList<String> getItems () {
return al;
}
By the way, it's generally better to specify the type parameter to ArrayList, e.g. ArrayList<Whatever>, as this can save you a lot of casting things around / unchecked conversions and will give you compile-time checking of types.
Is there a reason that you have to return an ArrayList? Essentially, you are trying to create a method that takes a deck, picks a card, and then returns a deck. You could try and use the subList method someone mentioned above. You could create a new ArrayList containing only the card you want, but that's not very efficient. Or, if your goal is to actually return the whole deck, but with the correct card on top (aka in the first position of the ArrayList), there's lots of info about rearranging values in an ArrayList online.
EDIT: Based on your full code, it looks like the goal is to flip the first card face up. You should do that (not gonna do your homework for you!) and then return the ArrayList that the method took in. IRL, imagine handing someone a deck, they flip the first card face up, then hand the deck back to you.
//ADDING AND deleting employees
//Displaying employee list
public class EployeeDB {
static ArrayList e = new ArrayList<>();
public static boolean addEmployee(Employee e1) {
e.add(e1);
System.out.println("Employee added");
return true;
}
public static boolean deleteEmployee(int ecode) {
int temp = 0;
for (int i = 0; i < e.size(); i++) {
if (e.get(i).getID() == ecode) {
temp = temp + 1;
e.remove(i);
break;
}
}
if (temp == 1)
System.out.println("Emp deleted");
else
System.out.println("Deletion unsuccessful, check ecode again");
return true;
}
public static String showPaySlip(int ecode) {
double salary = 0;
int temp = 0;
for (int i = 0; i < e.size(); i++) {
if (e.get(i).getID() == ecode) {
temp = temp + 1;
salary = e.get(i).getSalary();
break;
}
}
if (temp == 1)
return "Salary is" + salary;
else
return "No employye found with the specified ecode";
}
public static ArrayList<Employee> listAll() {
return e;
}
public static void main(String[] args) {
Employee e1 = new Employee();
e1.setID(20);
e1.setName("sai");
e1.setSalary(150.00);
addEmployee(e1);
Employee e2 = new Employee();
e2.setID(30);
e2.setName("kumar");
e2.setSalary(1500.00);
addEmployee(e2);
deleteEmployee(30);
System.out.println(showPaySlip(30));
for (int i = 0; i < e.size(); i++)
System.out.println(
listAll().get(i).getID() + " " + listAll().get(i).getName() + " " + listAll().get(i).getSalary());
}
}

Categories