how to delete an element of array without duplicating elements? - java

I need to delete a student at a certain index from an array so I am deleting this student and shifting the elements to the left but my problem is one element is duplicating. note that not all my array is full I am filling it through the program so maybe the last student is not the last element in my array '
public static void removestudent(int index) {
for (int j = index; j < employee.length - 1; j++) {
employee[j] = employee[j + 1];
}
System.out.println("The student was removed successfully");
}
}

The value gets duplicated as you are assigning employee[j] = employee[j + 1]; so when loop terminates the employee[j + 1] remains unchanged! so duplicate values. After loop assign employee[j + 1] to empty.

From your code, looks like the last two elements, at positions employee[j] and employee[j+1] resp. are getting duplicated.
You must remove the element at employee[j+1] because its already been copied to the location employee[j].
My recommandation is to use ArrayList, because it already handles this kind of situations.
_Thanks,
Bhushan

public static void removestudent(String index) {
int temp[];
for (int j = 0; j < employee.length - 1; j++) {
if(j<index){
temp[j] = employee[j];
}else
{
temp[j] =employee[j++];
}
}
System.out.println("The student was removed successfully");
employee = temp;
}
}

You can follow different approach.simply like this....!
public static void main(String args[]) {
String [] employee={"a","b","c","d","e"};
Set<String> s =new LinkedHashSet<String>();
int index=4;
for(int i=0;i<employee.length;i++)
{ if(i!=index)
{
s.add(employee[i]);
}
}
System.out.println(s);
System.out.println("The student was removed successfully");
}

Related

How can I eliminate/remove a duplication of an object array element which is duplicated a ton of time in the array. (Return same array type)

I tried this for loop but when for duplicated element in the array the inner loop breaks and if more than 10 repeated element are place in the array then the outer-loop brakes.
I need to return an array of same object type since I need to use the methods to pick some values from it.
public Mode insT(Guide[] guide){
Guide[] guideVo = checkGuideDuplication(guide);
}
public Guide[] checkGuideDuplication (Guide[] guide){
for(int i = 0; i<guide.length-1; i++){
for(int j = i+1; i<guide.length; i++){
if(guide[i].getGuide().trim().equals(guide[j].getGuide().trim())){
guide = (Guide[]) ArrayUtils.remove(guide);
}
}
}
return guide;
}
You need to reset the inner index once you remove an element so it gets checked (and bounds-checked) again:
guide = (Guide[]) ArrayUtils.remove(guide);
j--;
You can avoid the inner loop entirely if you use a map to weed out duplicates:
public Guide[] checkGuideDuplication (Guide[] guide){
Map<String, Guide> uniques = new HashMap<>();
for(Guide g : guide){
uniques.putIfAbsent(g.getGuide().trim(), g);
}
return uniques.values().toArray(new Guide[0]);
}
The most performing O(N) solution would be to use Map as shown in shmosel's answer.
But if using Map is not an option due to some constraints/limitations (e.g. only arrays are allowed), another solution would be to set removed elements to null and count the number of deletions, then shift nulls to the end of the array and return a truncated array:
public Guide[] checkGuideDuplication (Guide ... guide) {
int deleted = 0;
for (int i = 0; i < guide.length-1; i++) {
if (null == guide[i]) {
continue;
}
String currGuide = guide[i].getGuide().trim();
for(int j = i + 1; j < guide.length; j++) {
if (null == guide[j]) {
continue;
}
if (currGuide.equals(guide[j].getGuide().trim())) {
guide[j] = null;
deleted++;
}
}
}
// shift remaining elements
for (int i = 0, j = 0; i < guide.length; i++) {
if (guide[i] != null) {
guide[j++] = guide[i];
}
}
return Arrays.copyOf(guide, guide.length - deleted);
}

JAVA 2D Array Loop Print Formatting [0][0], [1][1], etc

I am having trouble getting my 2D array to print side by side values taking the first array row value index 0 and matching it to the 2nd row array index 0 and continuing on in a vertical list. As it stands, my code compiles and just prints the entire arrays in a horizontal fashion on two lines. Basically, I would like the end result to be formatted like this:
Admin | Password1
Vale.Vicky | BruceIsTheBat!
Lane.Lois | FlyMeToTheMoon1234
Kent.Clark | PhoneBoothsSmell
Wayne.Bruce | ThisBat4You99
...and so on.
public class PasswordArrays { // start of class
public static void main(String[] args) { // Start of main
// TODO Auto-generated method stub
String [][] idArray = {
{"Admin", "Vale.Vicky", "Lane.Lois", "Kent.Clark", "Wayne.Bruce", "Parker.Peter", "Rogers.Steve", "Luther.Lex", "Osborn.Harry","Prince.Diana", "Linda Zoel"},
{"Password1", "BruceIsTheBat!", "FlyMeToTheMoon1234", "PhoneBoothsSmell","ThisBat4You99", "webSlinger","ShieldEnthusiast", "HairClub4Men", "GoblinGoober", "WonderWonderWho?", "WhoIsLindaZoel?"}
};
printArray(idArray);
} //End of main
public static void printArray(String a [][]) { //start of printArray method
for (int row=0; row < a.length ; row++) { // start of row for loop
for (int column = 0; column < a [row].length; column++) { //start of column for loop
System.out.print(a[row][column] + " ");
} // End of column for loop
System.out.println();
} // End of row for loop
} // End of printArray method
} //End of class
I know there's got to be an answer already for this somewhere but I have been unsuccessful in finding it. Any help is greatly appreciated.
A 2D array could be iterated in two ways:
Row wise
Column wise
As per your expected result, what you would want to do is iterate column wise rather than row wise. Here's a solution:
public static void printArray(String a [][]) {
for(int col=0; col < a[0].length; col++) {
for (int row = 0; row < a.length; row++) {
if (row!=a.length-1) {
System.out.print(a[row][col] + "|");
}
else {
System.out.print(a[row][col]);
}
}
System.out.println();
}
}
Helpful Link: Iterate through multi-dimensional array
you are traversing your 2D array incorrectly
you can try this for your array:
if(a.length > 0){
for(int i = 0; i < a[0].length; i++){
for(int j = 0;j < a.length; j++){
System.out.print(a[j][i]+" ");
}
System.out.println("");
}
}
Structure
Are you sure that you understood the structure of your 2d-array? You only have two rows but multiple columns (the array contains 2 arrays containing multiple elements each).
The structure is
idArray = { /* firstArray, secondArray */ }
idArray[0] = { /* Names */ }
idArray[1] = { /* Passwords */ }
Solution
You only need one iteration from int i = 0; to i < idArray[0].length. After that always pair the content of idArray[0][i] with idArray[1][i], that's all.
final int[][] idArray = ...
// Variant 1: Regular for-loop
for (int i = 0; i < idArray[0].length; i++) {
System.out.println(idArray[0][i] + " | " + idArray[1][i];
}
// Variant 2: Stream solution
IntStream.range(0, idArray[0].length) // IntStream
.map(i -> idArray[0][i] + " | " + idArray[1][i]) // Stream<String>
.forEach(System.out::println);
Note that idArray[0].length and idArray[1].length should of course be equal.
Notes
Probably you are better off using proper OOP, creating classes for each Account containing name and password fields and then using a List<Account> and toString for Account or something like that.
public class Account {
private final String mName;
private final String mPassword;
public Account(final String name, final String password) {
this.mName = name;
this.mPassword = password;
}
public String getName() {
return this.mName;
}
public String getPassword() {
return this.mPassword;
}
#Override
public String toString() {
return this.getName() + " | " + this.getPassword();
}
}
And then use it like
final List<Account> accounts = new ArrayList<>();
accounts.add(new Account("Admin", "Password1"));
...
// Variant 1: Enhanced for-loop 'foreach'
for (final Account account : accounts) {
System.out.println(account);
}
// Variant 2: The same using streams
accounts.forEach(System.out::println);
// Variant 3: Using Lists 'toString'
System.out.println(accounts);

IndexOutOfBoundsException in ArrayList Java

Whenever I try to run the code I get IndexOutOfBoundsException. I have tried numerous of ways fixing it but none of them have helped. The method should add a new String element "****" into ArrayList before every String which's length is equal to 4. In this case, it must add "****" before "5555".
Where could be the problem?
import java.util.ArrayList;
public class Main {
public static ArrayList<String> markLength4(ArrayList<String> list) {
int sum = 0;
for ( int i = 0; i < list.size(); i++) {
if (list.get(i).length() == 4) {
list.add(list.indexOf(i), "****");
}
}
return list;
}
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("ddddddddddddd");
list.add("fffffffffffff");
list.add("5555fdgdfg");
list.add("5555");
list.add("5555");
System.out.println(markLength4(list));
}
}
list.indexOf(i) will return -1, since i doesn't appear in your list. Therefore adding an element at the -1 position will throw an exception.
If you change list.add(list.indexOf(i), "****") to list.add(i, "****");, you'll get an infinite loop that will end with OutOfMemoryError, since the newly added String also has a length() of 4, so another String will be added on the next iteration, and so on.
i is not in your arraylist - it is a list of String, not Integer. That means that list.indexOf(i) == -1.
From your description, I think you mean:
list.add(i, "****");
but you will also need to increment i, e.g.
list.add(i++, "****");
to avoid the infinite loop that Eran mentions.
Or, of course, you can iterate the list backwards, and avoid the infinite loop/need to change the loop variable inside the loop body:
for ( int i = list.size() - 1; i >= 0; i--)
{
if (list.get(i).length() == 4)
{
list.add(i, "****");
}
}
import java.util.ArrayList;
public class Test {
public static ArrayList<String> markLength4(ArrayList<String> list) {
int sum = 0;
for (int i = 0; i < list.size(); i++) {
if (list.get(i).length() == 4) {
list.add(i++, "****");
}
}
return list;
}
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("ddddddddddddd");
list.add("fffffffffffff");
list.add("5555fdgdfg");
list.add("5555");
list.add("5555");
list = markLength4(list);
for (String x : list) {
System.out.println(x);
}
}
}
You'll loop forever this way, because there's 4-lengthened strings forward and you keep adding...
You can solve this by looping from the end, but you'll have to be careful with your index(you should add and increment the index to avoid that)
After Editing list.add(i++,"****"); the code should work just fine.
Notable
If you want to add before use i++;.
If you want to add after your match use ++i;.
list.indexOf(i) is not present in the list . It will produce -1
-1 is not available in ArrayList
Replace the Line
list.add(list.indexOf(i), "****");
with the following line
list.set(i, "****");
It replace the existing content of the List with new element in the index of i with new element i.e (****)
list.indexOf(i) where i is an int and therefore not in your list will throw your error as stated in comments (index -1).
use either of the following:
list.add("str") to add a String to the end of the list
OR
list.set(i, "****") which will set the value at a given index to this new string.
In the markLength4 method, by adding the element in the for loop you keep adding Strings and increasing the list size. You need a flag that tells the index and then ends the loop. You can try something like that
public static ArrayList<String> markLength4(ArrayList<String> list) {
int i = 0;
boolean found = false;
int pos = 0;
while(i < list.size() && !found){
if (list.get(i).length() == 4) {
found = true;
pos = i;
}
i++;
}
list.add(pos, "****");
return list;
}

How can I avoid the user to add a repeated int value to an array?

First of all, I'm trying to do this using only simple conditions since I don't know how to use Hashmaps.
Ok, here is what I got so far, but I got stuck. Do you guys know a way in which I can compare an int to all the ints in an array?
public void rep() throws IOException {
for (int i = 0; i < arr.length; i++) {
System.out.println("Enter the value for the position # " + (1+i) + " of the array.");
int lol = Integer.parseInt(entrada.readLine());
if(!Arrays.Equals(arr[i], lol))
arr[i] = Integer.parseInt(entrada.readLine());
}
}
You can try this:
boolean repeat = false;
for(int j=0; j<i; j++ )
{
if(arr[j] == lol)
{
repeat = true;
break;
}
}
if(!repeat)
arr[i] = Integer.parseInt(entrada.readLine());
you can use the following method
for(i=0;i<intArray.length;i++){
if(intValue==intArray[i])
{ //write codes for if }
else{
// write codes for else }
You can do
java.util.Arrays.asList(arr).contains(lol)
what the above function is doing it coverts the array to list and the apply contains method to check if element is present

How to remove an element from an array

In Java, The teacher taught us how to remove an element from an array without using array utils and so on. So I tried the method he gave to us. It updates the index value exactly as I want. after it changes the index value, I want it to delete the last index, "sizeOfArray-1"
but I couldn't do that! Any help?
Here the code:
import java.util.Scanner;
public class Arrays {
static int x[] = { 1, 2, 3, 4, 5, 6, 7 };
static Scanner input = new Scanner(System.in);
public int search(int target) {
for (int index = 0; index < x.length; index++) {
if (x[index] == target)
return index;
}
return -1;
}
public void deleteIndex(int target) {
int deleted = search(target);
if (deleted == -1)
System.out.println("Entry Not Found!");
else {
x[target] = x[7-1];
}
}
public static void main(String[] args) {
Arrays f = new Arrays();
int counteri = 0;
int counterj = 0;
for (int j = 0; j < x.length; j++) {
System.out.print(counterj + "=>" + x[j] + " \n");
counterj++;
}
f.deleteIndex(input.nextInt());
for (int i = 0; i < x.length; i++) {
System.out.print(counteri + "=>" + x[i] + " \n");
counteri++;
}
}
}
First of all you have to change this line
x[target] = x[7-1];
to this :
x[deleted] = x[7-1];
because you find an element in your search function, and return its index to deleted so you have to do your action in x[deleted] not x[target]
Your code just replace the actual value of element with amount of last element in here :
else {
x[target] = x[7-1];
}
So when you want to (so as you call it) delete the last element it just replace last element with it self so it didnot do anything.
You can just simply assign another value that doesnt exist in your array for instance -1 and you could see your function works as you want.
a thing like this :
else {
x[deleted] = -1;
}
But it is not delete actually, and you cant delete items of array in java.
You really cannot delete an item from an array in Java. Here is some pseudo code that shows what you can do instead:
create a new array that has size -1 of the original array
start looping, keep track of the current index
copy the item(s) from the original array to the new array corresponding to the current index if it should be kept (otherwise skip the item that should be removed)
return the new array
An array in Java has fixed predefined length, once you initialize the array you cannot actually remove an element from it. The best thing you can do is to create another array containing all the elements of the original array without that specific one.
//delete the element the perticular element in a position//
import java.util.*;
class main13
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the range");
int no=sc.nextInt();
System.out.println("Enter the array elements");
int a[]=new int[no];
int i,j;
for(i=0;i<no;i++)
{
a[i]=sc.nextInt();
}
System.out.println("Enter the element you want to delete");
int d=sc.nextInt();
for(i=0;i<no;i++)
{
if(d==a[i])
{
for(j=i;j<no-1;j++)
{
a[j]=a[j+1];
}
break;
}
else
{
System.out.println("Element not found");
System.exit(0);
}
}
System.out.println("After deletion:");
for(i=0;i<no-1;i++)
{
System.out.println(a[i]);
}
}
}

Categories