I am trying to populate a java string array with a variable. the variable contains values which I am reading in from a text file. every time a new value is stored in the array the current value is replaced by the new value.
the code below is what i have tried so far.
int n = 0;
String var1 = value;
String array[] = {var1};
String [] array = new String[n];
for (int i =0; i < n; i++) {
array[n++] = value;
}
Java has only fixed sized arrays; dynamically growing "arrays" are realized with List:
List<String> array = new ArrayList<>();
for (int i = 0; i < 42; ++i) {
String s = "" + i;
array.add(s);
}
for (String t : array) {
System.out.println(t);
}
String seven = array.get(7);
int n = array.size();
if (array.isEmpty()) { ... }
// In Java 8:
array.stream().sorted().forEach(System.out::println);
Using (fixed sized) arrays would be cumbersome:
String[] array = new String[];
String[] otherVar = array;
for (int i = 0; i < 42; ++i) {
String s = "" + i;
array = Arrays.copyOf(array, i + 1);
array[i] = s;
}
Here on every step a new array is created, the content of the old array copied.
Also notice that otherVar keeps the initial empty array.
Note that String[] a is the same as String a[]. The latter is only for compatibility to C/C++, and is less readable.
This will add a string indefinitely. When you read all the data from file you have to set isFileNotEnded = false
boolean isFileNotEnded = true;
List<String> array = new ArrayList<>;
while (isFileNotEnded) {
array.add("hello");
//stop here the infinite loop
}
Related
I am working with String and String[] in java.
I have one String[] and wanted to convert into String but don't want last index value in it.
String[] arr = new String[]{"1","2","3","4"};
I want new string as 123 only.
Yes, I can iterate arr up to second last index maintain assign the value in the new string. But is there any other way to this thing in the smarter way?
I think about three ways.
First one is using StringBuilder. This takes you full control with minimum garbage. (I would prefer this one)
public static String convert(String... arr) {
// in case of arr is really big, then it's better to first
// calculate required internal buffer size, to exclude array copy
StringBuilder buf = new StringBuilder();
for(int i = 0; i < arr.length - 1; i++)
buf.append(arr[i]);
return buf.toString();
}
Another way is to use Java8 feature String.join():
public static String convert(String... arr) {
return String.join("", arr).substring(0, arr.length - 1);
}
And finally using Stream:
public static String convert(String... arr) {
return Arrays.stream(arr, 0, arr.length - 1).collect(Collectors.joining(""));
}
try this
String[] arr = new String[]{"1","2","3","4"};
String newString = "";
for (int i = 0; i < arr.length -1 ; i++) {
newString += arr[i];
}
System.out.print(newString);
Output
123
I have a
List<ArrayList> arg = new ArrayList<ArrayList>();
with
[[logo], [cd_branche], [lib_branche]],
(other arguments not relevant)
[[1111,22222,3333]],[[2222,324,432]]...
and I want to cast it to a String[] so I did this
Object[] obj = arg.toArray();
String[] headers =new String[obj.length];
for(int i=0;i<headers.length;i++) {
headers[i]= (String) obj[i];
}
but I'm getting
java.util.ArrayList cannot be cast to java.lang.String
The output I'm looking for is
headers[0]=logo
headers[1]=cd_branche
headers[2]=lib_branche
Using Java 6
It sounds like you want it to be an array of strings (i.e. "[["logo", "cd_branche", "lib_cranche"],[..],[..],[1111,22222,3333],[2222,324,432]").
In that case simply do:
Object[] obj = arg.toArray();
String[] headers =new String[obj.length];
for(int i=0;i<headers.length;i++) {
headers[i]= Arrays.toString(obj);
}
And each one of your ArrayList objects inside obj will be returned in string array format.
UPDATE: Since you want it as a flat array, you'll need to (a) compute the size of the array needed and (b) run through your object with two loops and make a deep search as such:
int size = 0;
for (int i = 0; i < arg.size(); size += arg.get(i++).size());
String[] headers =new String[size];
for(int count = 0, i=0;i<arg.size();i++) {
for (int j=0; j< arg.get(i).size(); j++) {
headers[count++]= arg.get(i).get(j).toString();
}
}
String headers = "";
for (String header:arg)
{headers += header;}
static String[] TEST_NAMES = new String[]{"vectorTest",
"scalarMultiplicationTest", "columnVectorTest", "dotProductTest",
"matrixTest", "matrixMultiplicationTest", "selectRowTest",
"selectMaxTest", "indexOfMaxTest", "updateTest", "addItemTest",
"updateDatabaseTest"};
I want a loop that would iterate through this array and whenever it points at an index in the testNames array it should pass it as an 'E' on to another array and the final array should be passed to a 'resultString' variable which returns all 'E's to the database. This is what I have tried but it has errors cos they are incompatible types.
testNames = OOJavaBasics.TEST_NAMES;
ArrayList<Integer> zeroSubmission= new ArrayList<>();
for (int i = 0; i < testNames.length; i++) {
if (thirdLastLine.contains("OK (0 tests)") && testNames.equals(i)){
zeroSubmission.add('E');
resultString = zeroSubmission;
System.out.println(resultString);
}
}
The output should be the total number which is 12 of the array length in E like this 'EEEEEEEEEEEE'
You can do it using only a String instead of having a second array.
Try the following:
testNames = OOJavaBasics.TEST_NAMES;
String resultString="";
for (int i = 0; i < testNames.length; i++) {
if (thirdLastLine.contains("OK (0 tests)") && testNames[i].equals("wanted result")){ // do not compare an Array with an int in the .equals()
resultString += "E";
}
}
System.out.println(resultString);
Everytime you find the wanted result, you directly add an "E" to your resultString.
EDIT:
Referring to your last EDIT, the solution is very simple:
for (int i = 0; i < testNames.length; i++) {
resultString += "E";
}
Just loop through the array and add an E to the resultString in each iteration.
This is how I solved it
String E = "";
if (thirdLastLine.contains("OK (0 tests)")) {
System.out.println(thirdLastLine);
for (int i = 0; i < testNames.length; i++) {
E += 'E';
}
resultString = E;
System.out.println(resultString);
}
I want to shift each elements in array to left if there is a null. E.g
public static void main(String[] args) {
String asd[] = new String[5];
asd[0] = "zero";
asd[1] = "one";
asd[2] = null;
asd[3] = "three";
asd[4] = "four;
I want the output to be
zero, one, three, four.
The length should also be adjusted
How can i do this using loops? I tried using if statements to check if an element is not null copy that value to another array. But i dont know how to copy if there is a null.
Given the kind of question, I suppose you want a simple, loop only and array only based solution, to understand how it works.
You have to iterate on the array, keeping an index of the new insertion point. At the end, using that same index, you can "shrink" the array (actually copy to a new smaller array).
String[] arr = {"a","b",null,"c",null,"d"};
// This will move all elements "up" when nulls are found
int p = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == null) continue;
arr[p] = arr[i];
p++;
}
// This will copy to a new smaller array
String[] newArr = new String[p];
System.arraycopy(arr,0,newArr,0,p);
Just tested this code.
EDIT :
Regarding the possibility of shrinking the array without using System.arraycopy, unfortunately in Java arrays size must be declared when they are instantiated, and can't be changed (nor made bigger nor smaller) after.
So if you have an array of length 6, and find 2 nulls, you have no way of shrinking it to a length of 4, if not creating a new empty array and then copying elements.
Lists can grow and shrink, and are more handy to use. For example, the same code with a list would be :
String[] arr = {"a","b",null,"c",null,"d"};
List<String> list = new ArrayList<>(Arrays.asList(arr));
Iterator<String> iter = list.iterator();
while (iter.hasNext()) if (iter.next() == null) iter.remove();
System.out.println(list);
Try:
int lengthNoNull = 0;
for(String a : asd) {
if(a != null) {
lengthNoNull++;
}
}
String[] newAsd = new String[lengthNoNull];
int i = 0;
for(String a : asd) {
if(a != null) {
newAsd[i++] = a;
}
}
Piece of code using only arrays.
String[] x = {"1","2","3",null,"4","5","6",null,"7","8","9"};
String[] a = new String[x.length];
int i = 0;
for(String s : x) {
if(s != null) a[i++] = s;
}
String[] arr = Arrays.copyOf(a, i);
Or this:
String[] xx = {"1","2","3",null,"4","5","6",null,"7","8","9"};
int pos = 0, i = 0;
String tmp;
for(String s : xx) {
if(s == null) {
tmp = xx[pos];
xx[pos] = s;
xx[i] = tmp;
pos++;
}
i++;
}
String[] arr = Arrays.copyOfRange(xx, pos, xx.length);
How do I concatenate, or append, all of the arrays that contain text strings into a single array? From the following code:
String nList[] = {"indonesia", "thailand", "australia"};
int nIndex[] = {100, 220, 100};
String vkList[] = {"wounded", "hurt"};
int vkIndex[] = {309, 430, 550};
String skList[] = {"robbed", "detained"};
int skIndex[] = {120, 225};
String nationality = "";
//System.out.println(nationality);
I want to store all strings of all three string-containing arrays:
String nList[] = {"indonesia", "thailand", "australia"};
String vkList[] = {"wounded", "hurt"};
String skList[] = {"robbed", "detained"};
into a single array, say array1[].
ArrayList<String> temp = new ArrayList<String>();
temp.addAll(Arrays.asList(nList));
temp.addAll(Arrays.asList(vkList));
temp.addAll(Arrays.asList(skList));
String[] result = (String[])temp.toArray();
You can add the content of each array to a temporary List and then convert it's content to a String[].
List<String> temp = new ArrayList<String>();
temp.addAll(Arrays.asList(nList));
temp.addAll(Arrays.asList(vkList));
temp.addAll(Arrays.asList(skList));
String[] result = new String[temp.size()];
for (int i = 0; i < temp.size(); i++) {
result[i] = (String) temp.get(i);
}
Alternatively, you can use Guava's ObjectArrays#concat(T[] first, T[] second, Class< T > type) method, which returns a new array that contains the concatenated contents of two given arrays. For example:
String[] concatTwoArrays = ObjectArrays.concat(nList, vkList, String.class);
String[] concatTheThirdArray = ObjectArrays.concat(concatTwoArrays, skList, String.class);
public static String[] join(String [] ... parms) {
// calculate size of target array
int size = 0;
for (String[] array : parms) {
size += array.length;
}
String[] result = new String[size];
int j = 0;
for (String[] array : parms) {
for (String s : array) {
result[j++] = s;
}
}
return result;
}
Just define your own join method. Found # http://www.rgagnon.com/javadetails/java-0636.html