here is my code and I need to remove a fruit from the array
public void delete(String fruitName) {
for (int i = 0; i < fruits.length; i++) {
if ( fruits[i].equals(fruitName)) {
fruits[i] = fruits[i+1];
break;
}
}
// ["banana", "apple, "Mango"] if removed banana then output ["apple", "Mango"].
// TODO: 1. implement this method.
/* TODO: 2. you may need to consult Java API documentation for the String class.
* Write a comment in the code, the method of the String class you
* look up and the URL to the documentation the method
*/
}
"Working code Example : "(Execution)
public class DeleteValue {
String fruits[] = { "apple", "orange", "banana", "mango", "Cherries", "Blueberries" }; // array of fruits
public void delete(String fruitName) {
// printing array of fruits before deletion
System.out.println("\nAvailable fruits Before delete : " + fruits.length + "\n");
for (String s : fruits) {
System.out.println(s + " is Available\n");
}
int length = fruits.length;
int lengthNew = length;
int countNull = 0;
// 1. Find and delete the fruit
for (int i = 0; i < fruits.length; i++) {
if (fruits[i] == fruitName) {
fruits[i] = null;
break;
}
}
// count the null or deleted values so that we can create a new array of length
// minus the deleted fruit
for (int i = 0; i < fruits.length; i++) {
if (fruits[i] == null) {
countNull++;
}
}
// new array length
lengthNew = lengthNew - countNull;
// create new array of fruits
String newFruits[] = new String[lengthNew];
// assigning values from original array to new
int j = 0;
for (int i = 0; i < fruits.length; i++) {
if (fruits[i] == null) {
continue;
}
if (fruits[i] != null) {
newFruits[j] = fruits[i];
j++;
}
}
System.out.println("------------------------------------------");
System.out.println("\nAvailable fruits after delete : " + newFruits.length + "\n");
// print the final output
for (String s : newFruits) {
System.out.println(s + " is Available\n");
}
}
public static void main(String args[]) {
new DeleteValue().delete("mango");
;
}
}
Explanation :
The only Issue I am having its that Fruit Array is not decreasing the
size
An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed
So what we can do is either use a dynamic array or we can use a work around like the above code:
If you want to "grow" or "shrink" an existing array, you have to allocate a new array of the appropriate size and copy the array elements from old array to the new array.
In the above code I have provided comments for the working steps.
We are solving this problem is three steps:
Find and delete the fruit item from array.
count the deleted values from old array so that we can create a new array
of that size.
Move all remaining items from old array to new array.
Related
I have this question here
Once a player has drawn the top card from the deck, they must discard it.
Given a deck of cards, return a new deck containing all the cards except the first from the original deck.
Note: The new array returned is one element shorter than the original, except when the deck has no cards. Then the array returned must be empty.
So basically I have to make a new array thats the same as the old array minus the card at index 0. The issue im having is when I have to put an empty array and IntelliJ keeps throwing a NegativeArraySizeException.
public String[] discardTopCard(String[] remainingDeck) {
String[] newHand = new String[remainingDeck.length - 1];
String[] emptyArray = new String[] {};
int k = 0;
if (remainingDeck.length == 0 || remainingDeck.length == 1) {
return emptyArray;
}
for (int i = 1; i < remainingDeck.length; i++) {
newHand[k] = remainingDeck[i];
k++;
}
return newHand;
}
this is my current code.
I've also tried this and just setting it to null
public String[] discardTopCard(String[] remainingDeck) {
String[] newHand = new String[remainingDeck.length - 1];
int k = 0;
if (remainingDeck.length == 0 || remainingDeck.length == 1) {
return remainingDeck;
}
for (int i = 1; i < remainingDeck.length; i++) {
newHand[k] = remainingDeck[i];
k++;
}
return newHand;
}
If you want to work with a new array that is only part of an existing on, I would recommend to use an existing method: java.util.Arrays.copyOfRange
Example:
private static final String[] EMPTY_STRING_ARRAY = new String[0];
public String[] discardTopCard(String[] remainingDeck) {
int length = remainingDeck.length;
if (length < 2) {
return EMPTY_STRING_ARRAY;
}
return Arrays.copyOfRange(remainingDeck, 1, length);
}
I declared the empty string array as constant outside the method, because it is immutable and it's not necessary to create more than one instance in the whole program.
Both cases, empty input array and input array of lenght 1 will have the same result: an empty array.
Also note that usage of length in the copyOfRange method is OK because there it acts as "to"-index and not as number of elements to copy.
Or, even simpler:
public String[] discardTopCard(String[] deck) {
if (deck.length > 1)
deck = Arrays.copyOfRange(deck, 1, deck.length);
return deck;
}
How about this?
public String[] discardTopCard(String[] deck) {
if (deck.length == 0) {
return deck;
}
String[] smallerDeck = new String[deck.length - 1];
for (int i = 0; i < smallerDeck.length; i++) {
smallerDeck[i] = deck[i];
}
return smallerDeck;
}
In this program, I have to use the concept of polymorphism,
I have 1 abstract superclass named Data, and 2 subclasses named List and Single. Single accepts a double value(Constructor: public Single(value)). List accepts an array of doubles.( Constructor: List(double[] arr)), and in my main method, the following array,...
public static void main(String[] args) {
Object[] mixedData = {
new Single(2.4),
"The data is 3.6",
new List(new double[] {3.2,6.8}),
"Nothing here at all",
new List(new double[] {1.2,7.9,4.5}),
"Anda 1 anda 2 anda 3",
new Single(9.8) };
I have to convert this Object[] array into Data[] array using a method:
public static Data[] convert(Object[] objects){
final int MAX_LIST_SIZE = 10;
//***** YOUR CODE HERE *****
objects= new Object[MAX_LIST_SIZE];
Data[] data= new Data[MAX_LIST_SIZE];
data = (Data[]) objects;
for(int i=0; i<data.length; i++) {
}
return null; //Dummy statement - replace it
}
In this method,
1)we have to make sure that both arrays are of same length.
2)Use shallow copy
3)If there is a String(if it contains a number), then change it to List object, containing all the numbers that can be found(as separate tokens) in the String. Use a Scanner to scan the String for
numbers. Non-numbers should be ignored.
My Only doubt is that, in mixedData array, how can I find if it contains a String.
hope someone will answer.
I added some comments to your code to guide you through the solution.
public static Data[] convert(Object[] objects){
// If the objects array contains more than 10 elements what to do?
// final int MAX_LIST_SIZE = 10;
// Here you clear the content of the input objects, why?
//objects= new Object[MAX_LIST_SIZE];
// Set the length of data to the length of the input object array
Data[] data= new Data[objects.length];
// This cannot be done
// data = (Data[]) objects;
for(int i=0; i<objects.length; i++) {
if(objects[i] instanceof Single) {
data[i] = (Single) objects[i];
}else if(objects[i] instanceof List) {
data[i] = (List) objects[i];
}else if(objects[i] instanceof String) {
String string = (String) objects[i];
// Find all doubles with Scanner
// Add the doubles to a List
// Add the List to data[i]
}
}
return data;
}
Since both arrays are of same length, you have to decide how to handle an array element that doesn't contain a decimal number. For example, the interned String object "Nothing here at all" doesn't contain any numerical values, so once we process the string, it will return a null value.
Shallow copy: since the field is a primitive type (double), use the = operator to assign its value to the array at the right index.
You can change the code easily to implement the use of a Scanner to scan the String for numbers as required. Create a new scanner object and pass the string you're processing in the constructor.
/**
* Output:
* Single obj: 2.4
* Single obj: 3.6
* List obj: 3.2 6.8
* Data obj: null
* List obj: 1.2 7.9 4.5
* List obj: 1.0 2.0 3.0
* Single obj: 9.8
*
* #author martinfall
*/
public class TestData {
public static void main(String[] args) {
// Given
Object[] mixedData = {
new Single(2.4),
"The data is 3.6",
new List(new double[]{3.2, 6.8}),
"Nothing here at all",
new List(new double[]{1.2, 7.9, 4.5}),
"Anda 1 anda 2 anda 3",
new Single(9.8)};
// Convert mixedData and assign the result to a Data array
Data[] arr = convert(mixedData);
// Print to console (Not required but helpful to see the output of each obj)
for (Data datum : arr) {
if (datum instanceof Single) {
System.out.print("Single obj: ");
System.out.println(((Single) datum).value); // Can encapsulate
} else if (datum instanceof List) {
System.out.print("List obj: ");
for (double num : ((List) datum).arr) {
System.out.print(num + " ");
}
System.out.println();
} else {
// Since required that both arrays be equal size,
// not sure how to handle an element of mixedData that doesn't
// contain any decimal numbers
System.out.println("Data obj: " + datum);
}
}
}
public static Data[] convert(Object[] objects) {
// Find the length of objects and assign it to MAX_LIST_SIZE
final int MAX_LIST_SIZE = objects.length;
// Create a new array of Data objects using the length of objects
Data[] arr = new Data[MAX_LIST_SIZE];
// Loop throught the array and copy each element as required
for (int i = 0; i < MAX_LIST_SIZE; i++) {
if (objects[i] instanceof Single) {
arr[i] = (Data) objects[i]; // Shallow copy
} else if (objects[i] instanceof List) {
arr[i] = (Data) objects[i];
} else if (objects[i] instanceof String) {
// Since both arrays have to be the same length, we have to add
// the null value that is returned if a string doesn't contain
// a numerical value
arr[i] = processString((String) objects[i]);
}
}
return arr;
}
public static Data processString(String str) {
// Regular expression to match double values
String regex = "^[-+]?\\d*(\\.\\d+)?$";
// Counter variable to use to find out if list or single is returned
int count = 0;
// Create a blank Data variable
Data d = null;
// Split the String
String[] split = str.split(" ");
// Determine if Single or List
for (String s : split) {
if (s.matches(regex)) {
count++;
}
}
// If count is 1, return a Single
if (count == 1) {
for (String s : split) {
if (s.matches(regex)) {
d = new Single(Double.parseDouble(s));
}
}
} else if (count > 1) {
// Create a new array as large as count
double[] arr = new double[count];
// Index of arr
int arrIndex = 0;
for (String s : split) {
if (s.matches(regex)) {
arr[arrIndex] = Double.parseDouble(s);
arrIndex++;
}
}
d = new List(arr);
}
return (Data) d;
}
}
I have a .txt file which has data for states as given below:
AL,Alab,4860
AK,Alas,7415
AZ,Ariz,6908
AR,Arka,2988
I have made a function which counts how many states there are that start with the initial passed as such:
public int CInitial(char initial) {
int total = 0;
for(int i = 0; i < states.length; i++) { //states is an array which includes all states present in the .txt file
String testString = states[i].getName(); // getName gets the name of the states present in the .txt file
char[] stringToCharArray = testString.toCharArray();
for (char output : stringToCharArray) {
if(initial == output) {
total++;
}
}
}
return total;
}
This would return the number 4 if "A" is passed and 0 if any other initial is passed as there are 4 states that begin with the letter "A".
Now how can I create a new function that passes a character and returns the name of all the states that begin with that character? For Instance this is the initial return type needed for this, however I'm having troubles starting this. Is the process identical to the countStatesCountByInitial function I created?
public State[] CByInitial(char initial) {
return new State[] {}; //to be completed
}
Yes, it will be very similar to the countStatesCountByInitial. The main difference is each time you find a match, you want to add the state into the array. Since we don't know the size of the array beforehand, we may want to use a List instead.
public State[] getStatesCountByInitial(char initial) {
ArrayList<State> found = new ArrayList<>();
// this is the same as before
for(int i = 0; i < states.length; i++) {
String testString = states[i].getName();
char[] stringToCharArray = testString.toCharArray();
for (char output : stringToCharArray) {
if(initial == output) {
// except here when you find a match, you add it into the list
found.add(states[i]);
}
}
}
// return as array
return found.toArray(new State[found.size()]);
}
As suggested by Patrick, we can avoid using List by using countStatesCountByInitial to initialize the size of the states.
public State[] getStatesCountByInitial(char initial) {
int matchSize = countStatesCountByInitial(initial);
States[] found = new States[matchSize];
int foundIndex = 0;
// this is the same as before
for(int i = 0; i < states.length; i++) {
String testString = states[i].getName();
char[] stringToCharArray = testString.toCharArray();
for (char output : stringToCharArray) {
if(initial == output) {
// except here when you find a match, you add it into the array
found[foundIndex] = states[i];
foundIndex++;
}
}
}
// return the array
return found;
}
You can done both operations simply by one method.
public static ArrayList<State> getStatesCountByInitial(char initial) {
ArrayList selectedStates = new ArrayList<State>();
for(int i = 0; i < states.length; i++) {
if(states.charAt(0) == initial){
selectedStates.add(states[i]);
}
}
return selectedStates;
}
This method will return a arraylist.
If you want to get the count, call this method and get the size of the array.
ArrayList<State> statesNew = getStatesCountByInitial('A');
int count = statesNew.size();
I have a String named listOfItemsBanned, and an ArrayList named itemsBanned.
Let's say the ArrayList itemsBanned contains 3 things: TNT, EnderPearl, and Sand.
I would want the String to be "TNT, EnderPearl, Sand".
And when something is removed from itemsBanned, it would remove it from the string, too.
So.. I want to be able to get every item included in an ArrayList and put it into one String with each item separated by commas.
You need only one line:
String listOfItemsBanned = itemsBanned.toString().replaceAll("^.|.$", "");
toString() of List produces a CSV of the elements, but wrapped in [ and ]. The call to replaceAll() removes the first and last characters to leave just the elements.
You could do this:
String listOfItemsBanned = "";
for(int i = 0; i < itemsBanned.size(); i++){ //loop threw contents of itemsBanned (List<String>)
String s = itemsBanned.get(i); //get the string in itemsBanned (i)
listOfItemsBanned = listOfItemsBanned + "," + s; //add s to listOfItemsBanned
}
Now, if you would like to get all of the items that are banned from the string listOfItemsBanned, you could do:
String[] s = listOfItemsBanned.split(",");
//start the for loop at 1 because when saved it will be ",TnT,Sand,Enderpearl", notice the extra , in the begining
for(int i = 1; i < s.size(); i++){ //loop threw all of the items banned.
String itmBanned = s[i];
}
You could now do anything with itmBanned, like convert it to a Material:
Material m = Material.getMaterial(itmBanned);
So, you could do something like this for a remove method:
public void remove(String type){
String listOfItemsBanned = "";
itemsBanned.remove(type); //remove 'type' from the array
for(int i = 0; i < itemsBanned.size(); i++){
String s = itemsBanned.get(i);
listOfItemsBanned = listOfItemsBanned + "," + s; //reset the string to the new list
}
}
and for adding:
public void remove(String type){
String listOfItemsBanned = "";
itemsBanned.add(type); //add 'type' to the array
for(int i = 0; i < itemsBanned.size(); i++){
String s = itemsBanned.get(i);
listOfItemsBanned = listOfItemsBanned + "," + s; //reset the string to the new list
}
}
then you could check if the player is using a banned item, and cancel the event if they do, an example if they're using a banned block, like sand or TnT would be:
#EventHandler
public void playerInteract(PlayerInteractEvent e){
if(e.getAction.equals(Action.RIGHT_CLICK_AIR) || e.getAction.equals(Action.RIGHT_CLICK_BLOCK){
//the user has right-clicked
Material m = e.getItemInHand().getType(); //get the item in the user's hand
if(m != null){ //check that it's not null
if(listOfItemsBanned.contains(m.getName()){ //if listOfItemsBanned has the name of the item in the player's hand in it
e.setCanceled(true); //cancel the block place
}
}
}
}
Imports:
import java.util.Arrays;
import java.util.List;
Code:
public static void main(String args[]) {
String[] listOfItemsBanned = { "TNT", "EnderPearl", "Sand" }; // ArrayList
// of
// banned
// items
String output = ""; // Creates output String
for (int i = 0; i < listOfItemsBanned.length; i++) { // Loops through
// all items in
// the ArrayList
output += listOfItemsBanned[i]; // Adds item to String
if (i != listOfItemsBanned.length - 1) { // If it is not the last
// item in the ArrayList
// add ", "
output += ", ";
}
}
System.out.println(output); // Output String
}
Output:
TNT, EnderPearl, Sand
I need to compare the value from List with the value from array.
I wrote the following:
public class JavaApplication3 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic hereut
List<String> l = new ArrayList<String>();
l.add("test");
l.add("b");
String v = "";
String s = "";
String[] arr = {"test", "c", "b"};
for (int i = 0; i < l.size(); i++){
v = "";
s = "";
//System.out.println(l.get(i));
for (int j = 0; j < arr.length; j++){
if (l.get(i).equals(arr[j])){
s = i + "";
}else{
s = arr[i];
}
v = v + s + ",";
}
System.out.println(v);
}
}
}
I obtain the following
0,test,test,
c,c,1
but I need the result like this:
0, c, 1,
Looking at your expected result I guess the requirement like that:
for each element in the array, check if it is on the list. If it is on the list, print the index from the list for this element, otherwise print the element itself. So the algorithm should do:
array[0] = "test" -> found at index 0 -> print "0"
array[1] = "c" -> not found -> print "c"
array[2] = "b" -> found at index 1 -> print "1"
The outer loop should iterate over the array. Then, for each array item, iterate over the list until you find the same element. For a first draft, don't collect the output in a string but print it immediatly. You can create the string when the algorithm works as expected.
You have six iterations, each of which inserts something into the output.
You want three iterations, each of which checks for membership in the first list. You can do that with the List.contains() method. (If the list were long, you might want to consider using a Set instead of a List, to allow checking set membership more quickly.)
How about this:
public static void main(String[] args) {
// TODO code application logic hereut
List<String> l = new ArrayList<String>();
l.add("test");
l.add("b");
String v = "";
String s = "";
String[] arr = {"test", "c", "b"};
int pointer = 0;
for (int i = 0; i < l.size(); i++){
//System.out.println(l.get(i));
for (; pointer < arr.length;){
if (l.get(i).equals(arr[pointer])){
s = i + "";
v = v + s + ",";
pointer++;
break;
}else{
s = arr[i];
}
pointer++;
v = v + s + ",";
}
}
System.out.println(v);
}
Try to break things down to their high level steps.
For each string in the array
find its place in the list
if the item is in the list
print its position
else
print the missing string
print a common and space
Once you have this you can spot that find its place in the list could be a method that returns the place in the list or -1 if it isn't in the list. Here's what I made (might have renamed a few things and used a StringBuilder but you can ignore that for the moment).
import java.util.ArrayList;
import java.util.List;
public class Example {
public static void main(final String[] args) {
final List<String> listToSeach = new ArrayList<String>();
listToSeach.add("test");
listToSeach.add("b");
final String[] arrayElementsToFind = { "test", "c", "b" };
final StringBuilder output = new StringBuilder();
for (final String string : arrayElementsToFind) {
final int firstIndex = findFirstIndex(listToSeach, string);
if (firstIndex > -1) {
output.append(firstIndex);
} else {
output.append(string);
}
output.append(", ");
}
System.out.println(output);
}
private static int findFirstIndex(final List<String> list,
final String element) {
for (int i = 0; i < list.size(); i++) {
if (list.get(i).equals(element)) {
return i;
}
}
return -1;
}
}
Well I suggest this:
List<String> l = new ArrayList<String>();
l.add("test");
l.add("b");
String[] arr = {"test", "c", "b"};
for(int i=0;i<arr.length;++i){
if(l.contains(arr[i]))
s = ""+l.indexOf(arr[i]);
else
s = arr[i];
v = v + s + ",";
}
If got what you saying correct,I think this is less verbose