Only one Occurrence in Java - java

Scanner in = new Scanner(System.in);
x = new Scanner(new File("C:\\me.txt"));
int count = 0;
ArrayList<String> b = new ArrayList<>();
while((x.hasNext()))
{
String a = x.next();
int num = 0;
for(int i=0;i<count;i++)
{
if((b.get(i).equals(a)))
{num++;}
}
if(num==1)
{b.add(a);}
count++;
}
I want to add the element to b only when the occurence is only one. But there seems some error i keep getting.
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
Or does b.get(i) equal to NULL in first iteration?
if((b.get(i).equals(a)))

You got this error because b is empty it doesn't contain any element ,and you are trying to access element in it b.get(i) so you got java.lang.IndexOutOfBoundsException, use contains to find if the list have that element and if not add it to the list or use Set it doesn't allow duplicates
int count = 0;
ArrayList<String> b = new ArrayList<>();
while((x.hasNext()))
{
String a = x.next();
if(!b.contains(a)){
b.add(a);
}
count++;
}

Apparently you're trying to use count as the length of b. However, count is incremented more often than b is added to.
Possible solutions are:
Either update count only when you add something to b
or scratch count altogether and use b.size() in the for loop.

Please
check the line
if ((b.get(i).equals(a)));
It contains a semi-colon at the end and I think this is wrong: The next statement in curly braces (num++;) is executed every time and not only if the condition matches.
check if b.get(i) is null before calling equals on it. You know already that a is not null, hence it would make more sense to check for a.equals(b.get(i))
check the usage of count. Its value is not related to the size of the array list, but you use it this way in the loop.In your implementation a situation can arise in which the value of count is greater than the size of the list. This results in an IndexOutOfBoundsException.

Related

Java: Removing an empty Element from String Array [duplicate]

This question already has answers here:
Resize an Array while keeping current elements in Java?
(12 answers)
Closed 3 years ago.
I have an array String ar[] = {"HalloWelt", " "};, ar.length is 2.
It does register two values within "HalloWelt" on index 0, and a blank/empty string on index 1;
I wonder how can I remove empty space on the index 1 - > but also keep it as a String Array since it is necessary for next task. Or how to do bunch of conversions but end up with String Array in the end.
My attempt
public String[] arraysWhiteSpaceEliminator(String[] arr) {
int k=0; //Identify how big the array should be i.e. till it reaches an empty index.
for(int i=0; i<bsp.length;i++) {
arr[i].trim();
System.out.println(arr[i].isEmpty());
if(arr[i].isEmpty()) {
}
else {
k = k+1; //if the index isn't empty == +1;
}
}
String[] clearnArray = new String[k];
for(int s = 0; s<k; s++) {
clearnArray [s] = arr[s]; //define New Array till we reach the empty index.
//System.out.println(clearnArray [s]+" " +s);
}
return clearnArray ;
};
The logic is very simple:
Identify how big the clearnArray should be.
Iterate through original Array with .trim() to remove white Space and check wether isEmpty().
Add to the k if the index isnt Empty.
Create clearnArray with the k as size.
Loop through originial Array till k -> add all the items to cleanArray till k.
Issue: .trim() and .isEmpty() don't record that the index is empty. ?!
A solution with streams:
String[] clean = Arrays.stream(ar)
.map(String::trim)
.filter(Predicate.isEqual("").negate())
.toArray(String[]::new);
Note that this assumes none of the array elements are null. If this is a possibility, simply add the following stage before the map:
.filter(Objects::nonNull)
The problem with your code is that after counting to find k, you just write the first k elements from the original array. To solve the problem by your technique, you need to check each element of the input array again to see if it's empty (after trimming), and only write to the new array the elements which pass the test.
The code can be simplified using the "enhanced" for loop, since you don't need indices for the original array. (The variable i keeps track of the current index in the new array.) Note also that strings are immutable, so calling .trim() does nothing if you don't use the result anywhere. Your code also refers to bsp which is not defined, so I changed that.
int k = 0;
for(String s : arr) {
s = s.trim();
if(!s.isEmpty()) {
k++;
}
}
String[] cleanArray = new String[k];
int i = 0;
for(String s : arr) {
s = s.trim();
if(!s.isEmpty()) {
cleanArray[i] = s;
i++;
}
}
return cleanArray;
Calculate the number of non-null elements and create an array of that size, like
String[] strs = ...;
int count = 0;
for (int i = 0; i < strs.length; i++) {
if (strs[i] != null) count++;
}
String newStrArray[] = new String[count];
int idx = 0;
for (int i = 0; i < strs.length; i++) {
if (strs[i] != null) newStrArray[idx++] = strs[i];
}
return newStrArray;
You could also probably make this prettier using streams. However I haven't used streaming functionality in Java, so I can't help there.
Two things to note:
Unless you are serializing or the nulls are causing other problems, trimming the array just to get rid of the nulls probably won't have an impact on memory, as the size of an array entry (4 bytes) is very likely inconsequential to the memory block size allocated for the Array object
Converting first to an List and then back to an array is lazy and possibly inefficient. ArrayList, for example, will likely include extra space in the array it creates internally so that you can add more elements to the ArrayList and not have to create a whole new internal array.
in your method, create a new
List cleanedList = new ArrayList();
add iterate through ar[]ar[] = ["HalloWelt",""], and add only non-empty values to cleaned List....then return the array.
return cleanedList.toArray()
like below:
List<String> cleanedList = new ArrayList<>();
for(String s : arr) {
s = s.trim();
if(!s.isEmpty()) {
cleanedList.add(s);
}
}
return cleanArray.toArray();

Adding elements dynamically in String array but index 0 showing null?

I want to add some values in string array dynamically by using for loop.
when i debug the code at first for loop it is showing values which are adding.I want to check if any one of the string equals to my given value.but in for loop 2 at index 0 it showing null and at index 1 it showing the string value.
for(int i=0;i<someval;i++) {
String[] mylist = new String[someval];
mylist[i]=previousVal;
System.out.println("Previous Value : " +mylist[i]);
}
for (int j = 0; j <=mylist.length; j++) {
if (mylist[j].equals(givenValue) ) { {
System.out.println("your value found in the array");
}
}
The problem is that you are creating a new array using
mylist = new String...
during each loop iteration.
So, it doesn't really matter if you write something to an array, if the next step consists of throwing that array away.
In other words: make sure that you create the array just once; preferable before entering your loop.

Read and print sequences and print merged sequence

I suppose to write a Java program using array and method follows: It reads a sequence of strings, each on a separate line, and stores them in an array, let call it input1, with one string per cell, in the order they were read. The sequence ends with an empty line: one with a String of length 0. Same thing with 2nd sequence.Then prints the 1st sequence and 2nd sequence. And then create an array that contains all of the elements of the above two arrays. Merging is done by alternating between the arrays: that is, the first cell of input1 is copied followed by the first cell of input2. Then the second cell of input1 is copied followed by the second cell of input2. Of course, in general, the two sequences may have different lengths, so after the shorter sequence is finished, all elements of the longer sequence are simply appended to the output array. Finally, prints the merged array with 1 string each line.
import java.util.Scanner;
public class A4 {
public static void readInput(Scanner myScanner, String[] input) {
boolean streamEnded = false;
int index = 0;
while (!streamEnded && myScanner.hasNext()) {
String value = myScanner.nextLine();
if (value.length() == 0) {
streamEnded = true;
input[index] = value;
} else {
input[index] = value;
index++;
}
}
}
public static void main(String[] args) {
int size = 5;
String[] input1 = new String[size];
String[] input2 = new String[size];
String[] store = new String[size*2];
Scanner aScanner = new Scanner(System.in);
readInput(aScanner, input1);
for (int i = 0; i < input1.length; i++) {
System.out.println("input[" + i +"]" + input1[i]);
}
readInput (aScanner, input2);
for (int i = 0; i < input2.length; i++) {
System.out.println("input[" + i +"]" + input2[i]);
}
}
}
i still dont know how to merge those 2 inputs together.Can anyone show me how to do it? Thanks
Declare three arrays for sequence 1, sequence 2 and merged-sequence.
Use a variable whichToUse to store which array to be used and assign array1 to it before the while loop, then store values into array1 on the place of System.out.print, then when first reach value.length()==0 ('=' is not designed for comparing, it's a mistake in your code.), you change the whichToUse point to array2. When the second reach value.length()==0, end the reading loop. One place to be marked, declare streamEnded as a int to count how many times we reach the value.length()==0. Only exit loop while streamEnded==2.
Now you have two arrays which contains the values from file. Next step is to merge them. Use a for loop to iterate items in merged-sequence, and use loop-counter%2 to determine which array to read when assign value to merged-sequence items. after any of the array1 and array2 reaches the end, read the other array in the rest of loop.
As looks like you are new to Java, I think write code by yourself is much better than I provide the code to you. If you've any other question, just comment here.

How to delete an entry from an array in Java so that the other entries remain in order

Forgive the clunky title
I want to write a method that removes a specific entry from an array, but doesn't leave a null gap in the array. For example if a String array contained
|aa,bb,cc,dd,ee|
the user would be prompted to enter which number they wanted removed, the method would find the index of that entry, remove that index, then move the null entry to the last slot.
So if the user entered cc, the array's contents would be
|aa,bb,dd,ee,null|
EDIT: I realized I left out some information here. the entry I'm looking to remove will be passed from another method. I will then use a for loop to find the index of the entry (If not found nothing is done). However I'm stuck on how to do the deletion.
First of all: I strongly suggest to use an ArrayList where you can easily remove and add items without having to change the rest of the collection (it also has a toArray() method).
That being said, tihs would be a sample solution to do it with just arrays:
public static void main(String[] args) {
String[] arr = new String[5];
arr[0] = "aa";
arr[1] = "bb";
arr[2] = "cc";
arr[3] = "dd";
arr[4] = "ee";
System.out.println(Arrays.toString(arr));
int deleteIndex = 2;
System.arraycopy(arr, deleteIndex + 1, arr, deleteIndex, arr.length - deleteIndex - 1);
arr[4] = null;
System.out.println(Arrays.toString(arr));
}
Output:
[aa, bb, cc, dd, ee]
[aa, bb, dd, ee, null]
The idea is to to shift the elements one place ahead starting from the index to delete + 1. Afterwards you set the latest item manually to null or it will duplicate the last entry.
I would do it like this maybe:
for (int i = index; i < array.length -1; i++) {
array[i] = array[i+1];
}
array[array.length - 1] = null;
To keep the contents in order as you remove you need to shift elements to the left of the array.
The most naive and wasteful way would be to initialize another array with 1 size less than the current.
Then copy all the elements in a loop from your array but not the one that the user wants to remove (jumping that index)
You have the gist of it in your description
the user would be prompted to enter which number they wanted removed, the method would find the index of that entry, remove that index, then move the null entry to the last slot.
with not writing the actual code, since this seems like a school assignment, I'll just add what happens to the indexes of the rest of the entries after the deleted index?
One option would be to make the array into a List, remove the entry then make it into an array again.
ArrayList<String> aList = new ArrayList<String>(Arrays.asList(yourArray));
aList.remove(yourIndex);
return aList.toArray(new String[yourArray.length]);
As a Test example
public static void main(String[] args) {
String[] yourArray = new String[]{"FF","AA","BB"};
for(String s : yourArray)
System.out.println(s);
System.out.println("");
ArrayList<String> aList = new ArrayList<String>(Arrays.asList(yourArray));
aList.remove(1);
String[] r = aList.toArray(new String[yourArray.length]);
for(String s : r)
System.out.println(s);
}
Output
FF
AA
BB
FF
BB
null

Finding index of duplicate values in an ArrayList

I have an ArrayList which contains duplicate values at diff diff index.
for example {"Indian","American","Chinese","Australian","Indian","Russian","Indian"}
as u can see the value - "Indian" exists at index - 0, 4 & 6.
I need to know all these indexes where "Indian" exists and create an arrayList of that.
Here is my code:
public void filter(){
categoryArray = Arrays.asList(category);
for(String k : category){
//Log.v("filter", filterTerm);
if(k.equals(filterTerm.toLowerCase()))
{
int p = categoryArray.indexOf(k);
Log.v("index of categArr", ""+p);
String id = Integer.toString(p);
indexes.add(id);
}// end of if
}// end of for
Here I get how many times duplicate occurs by getting the size of indexes(ArrayList)
but when I check the values . Its one value at all index since in the method : indexOf() it always brings the index of first value that it finds in the Array.
So if duplicate exists at index - 2,5,7
I get the array size of index as 3.
But the values are {2,2,2,};
This is a situation where an index-based for loop is more appropriate than enhanced for loop that you're using, as what you need to grab is the index.
You can base all your work on the original array rather than converting it to a list, and I suspect you were going for case-insensitive match.
public void filter(){
for(int i=0; i<category.length; i++){
if(category[i].equalsIgnoreCase(filterTerm))
{
String id = Integer.toString(i);
indexes.add(id);
}
}
}
If you have an ArrayList rather than an array, of course similar code will work, but using list.get(i) instead of category[i].
You need to know which index in the array you are currently at, not the first index where it is to be found. To keep track of that, put
int i = 0;
before the loop, and at the very end of the loop put
i++;
Then the variable i tells you where you have found the value, so you can add i to the indexes list.

Categories