I am trying to instantiate the String array cool with items from the file "cool.txt" and the same for the array warm except with the text file "warm.txt" the program works to an extent however many elements of the array are labeled as null like this
This is partially correct as they array has all the correct items; just millions of null's after
here is my code
int count2=0;
int count3=0;
String[] filename ={"Cool.txt","Warm.txt"};
String[] cool =new String[30];
String[] warm =new String [3000];
String[][] arrays = new String [][]{cool,warm};
BufferedReader fr;
try
{
for(int i=0; i<2; i++)
{
fr = new BufferedReader(new FileReader(filename[i]));
String line = fr.readLine();
while (line != null)
{
if (i<=0)
{arrays[i][count2]=line;
System.out.println("COOL");
count2++;}
if(i>=1)
{arrays[i][count3]=line;
System.out.println("WARM");
count3++;}
line = fr.readLine();
}
fr.close();
}
System.out.println(Arrays.asList(warm));
System.out.println(Arrays.asList(cool));
}
catch(Exception F){
System.out.println("NUL");
}
}
When you create an array of objects in Java, they are initialized to a default value. For integers, this is 0. For Objects, such as String, this is a null-reference. As your array is made to contain 30000 elements, it will have the elements from your file (about 5), and the rest will not be initialized (null).
If you wish to use a list of Objects that has a variable size, you can look up ArrayLists, or other types of Lists. If you were to replace the following lines:
String[] cool =new String[30];
String[] warm =new String [3000];
and
System.out.println(Arrays.asList(warm));
System.out.println(Arrays.asList(cool));
with
List<String> cool = new ArrayList<String>();
List<String> warm = new ArrayList<String>();
and
System.out.println(warm);
System.out.println(cool);
You would get the correct result.
You were already using lists in a way: the method call Arrays.asList converts the argument to an object of the type List.
At the end of the function you end up converting them to list objects. If you just use a List to start with you won't have "millions" of nulls. The reason why you get nulls is you can only allocate the array one time, so all slots are defaulted to null.
Related
I want to randomize or shuffle the order of the string array using the code below
public static void main(String[] args) {
String str[]= {"Vxds", "Cvda", "Xcgi", "Atdr", "Mbeds", "0bda"};
String strTmp[]=str;
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i=0; i<str.length; i++) {
list.add(new Integer(i));
}
Collections.shuffle(list);
for (int i=0; i<str.length; i++) {
strTmp[i]=str[list.get(i)];
System.out.println(strTmp[i]);
}
}
The reason I do it like this instead of print it out directly is because I want to make it into a function later on. That's why I passed it to strTmp[] as that is what I want the function to return. But, the code just didn't function as I expected. It prints out several same value. How can I do it the right way? Thanks for the answer...
You almost had it, but you are referencing the same array twice and swap the contents of it. Change this line
String strTmp[] = str;
to
String strTmp[] = new String[str.length];
If you don't want to change the array str. Try this.
String str[] = {"Vxds", "Cvda", "Xcgi", "Atdr", "Mbeds", "0bda"};
String strTmp[] = str.clone();
Collections.shuffle(Arrays.asList(strTmp));
System.out.println(Arrays.toString(strTmp));
output
[Xcgi, Cvda, Atdr, Mbeds, 0bda, Vxds]
When you do String strTmp[]=str;, both str and strTmp are references to the same array. So when putting elements in, you are overwriting old elements including those have not yet been moved.
You may just do
String str[]= {"Vxds", "Cvda", "Xcgi", "Atdr", "Mbeds", "0bda"};
Collections.shuffle(Arrays.asList(str));
This works because Arrays.asList() does not create a new list, it merely provides a list view on the array. Any changes to the list change the array. Including shuffling it. Edit: This works for an array of strings and an array of any other reference type. As WJS points out, this will not work for an array of primitives (e.g., int[]) since Arrays.asList(arrayOfPrimitives) will create a list view of a newly created array of one elemeent, the primitive array.
If you require a new array with the shuffled strings and the old array unmodified, the solution is:
List<String> list = new ArrayList<>(Arrays.asList(str));
Collections.shuffle(list);
String[] newStr = list.toArray(new String[0]);
System.out.println("Original array: " + Arrays.toString(str));
System.out.println("New shuffled array: " + Arrays.toString(newStr));
Edit: Output from one example run:
Original array: [Vxds, Cvda, Xcgi, Atdr, Mbeds, 0bda]
New shuffled array: [0bda, Cvda, Mbeds, Vxds, Xcgi, Atdr]
As you can see, the original array is unmodified.
Edit: Since Java 11 it’s nicer to create the new array using Collection.toArray(IntFunction<String[]>):
String[] newStr = list.toArray(String[]::new);
See both code snippets run live in IdeOne.
I understand that you want to randomized your array in every execute. Here is the code for this.
import java.util.*;
public static void main(String[] args) {
String str[]= {"Vxds", "Cvda", "Xcgi", "Atdr", "Mbeds", "0bda"};
List<String> list =Arrays.asList(str);
Collections.shuffle(list);
System.out.println(list);
}
So i'm wondering if its possible to populate a String array made from toString() calls of an object ArrayList
So I know this can be done using a loop but is there a one line approach?
Loop approach
ArrayList<Object> objects = new ArrayList<Object>();
//fill object with elements
//
String[] strings = new String[object.length()];
for(int i = 0;i<10;i++)strings[i]=objects.get(i).toString();
Using java-8,
String[] strings = objects.stream().map(Object::toString).toArray(String[]::new);
I am fresher in java ,i have a doubt in java
that is
String array= new String[]{};
what is the use of { } here ?
what is the difference between String array=new String[]; and String array=new String[]{};
when I am writing String array=new String[10]{}; got error why?
Help me I am confused.
{} defines the contents of the array, in this case it is empty. These would both have an array of three Strings
String[] array = {"element1","element2","element3"};
String[] array = new String[] {"element1","element2","element3"};
while [] on the expression side (right side of =) of a statement defines the size of an intended array, e.g. this would have an array of 10 locations to place Strings
String[] array = new String[10];
...But...
String array = new String[10]{}; //The line you mentioned above
Was wrong because you are defining an array of length 10 ([10]), then defining an array of length 0 ({}), and trying to set them to the same array reference (array) in one statement. Both cannot be set.
Additionally
The array should be defined as an array of a given type at the start of the statement like String[] array. String array = /* array value*/ is saying, set an array value to a String, not to an array of Strings.
String array=new String[]; and String array=new String[]{}; both are invalid statement in java.
It will gives you an error that you are trying to assign String array to String datatype.
More specifically error is like this Type mismatch: cannot convert from String[] to String
You have a choice, when you create an object array (as opposed to an array of primitives).
One option is to specify a size for the array, in which case it will just contain lots of nulls.
String[] array = new String[10]; // Array of size 10, filled with nulls.
The other option is to specify what will be in the array.
String[] array = new String[] {"Larry", "Curly", "Moe"}; // Array of size 3, filled with stooges.
But you can't mix the two syntaxes. Pick one or the other.
TL;DR
An array variable has to be typed T[]
(note that T can be an arry type itself -> multidimensional arrays)
The length of the array must be determined either by:
giving it an explicit size
(can be int constant or int expression, see n below)
initializing all the values inside the array
(length is implicitly calculated from given elements)
Any variable that is typed T[] has one read-only field: length and an index operator [int] for reading/writing data at certain indices.
Replies
1. String[] array= new String[]{}; what is the use of { } here ?
It initializes the array with the values between { }. In this case 0 elements, so array.length == 0 and array[0] throws IndexOutOfBoundsException: 0.
2. what is the diff between String array=new String[]; and String array=new String[]{};
The first won't compile for two reasons while the second won't compile for one reason. The common reason is that the type of the variable array has to be an array type: String[] not just String. Ignoring that (probably just a typo) the difference is:
new String[] // size not known, compile error
new String[]{} // size is known, it has 0 elements, listed inside {}
new String[0] // size is known, it has 0 elements, explicitly sized
3. when am writing String array=new String[10]{}; got error why ?
(Again, ignoring the missing [] before array) In this case you're over-eager to tell Java what to do and you're giving conflicting data. First you tell Java that you want 10 elements for the array to hold and then you're saying you want the array to be empty via {}.
Just make up your mind and use one of those - Java thinks.
help me i am confused
Examples
String[] noStrings = new String[0];
String[] noStrings = new String[] { };
String[] oneString = new String[] { "atIndex0" };
String[] oneString = new String[1];
String[] oneString = new String[] { null }; // same as previous
String[] threeStrings = new String[] { "atIndex0", "atIndex1", "atIndex2" };
String[] threeStrings = new String[] { "atIndex0", null, "atIndex2" }; // you can skip an index
String[] threeStrings = new String[3];
String[] threeStrings = new String[] { null, null, null }; // same as previous
int[] twoNumbers = new int[2];
int[] twoNumbers = new int[] { 0, 0 }; // same as above
int[] twoNumbers = new int[] { 1, 2 }; // twoNumbers.length == 2 && twoNumbers[0] == 1 && twoNumbers[1] == 2
int n = 2;
int[] nNumbers = new int[n]; // same as [2] and { 0, 0 }
int[] nNumbers = new int[2*n]; // same as new int[4] if n == 2
(Here, "same as" means it will construct the same array.)
Try this one.
String[] array1= new String[]{};
System.out.println(array1.length);
String[] array2= new String[0];
System.out.println(array2.length);
Note: there is no byte code difference between new String[]{}; and new String[0];
new String[]{} is array initialization with values.
new String[0]; is array declaration(only allocating memory)
new String[10]{}; is not allowed because new String[10]{ may be here 100 values};
String array[]=new String[]; and String array[]=new String[]{};
No difference,these are just different ways of declaring array
String array=new String[10]{}; got error why ?
This is because you can not declare the size of the array in this format.
right way is
String array[]=new String[]{"a","b"};
1.THE USE OF {}:
It initialize the array with the values { }
2.The difference between String array=new String[]; and String array=new String[]{};
String array=new String[]; and String array=new String[]{}; both are
invalid statement in java.
It will gives you an error that you are trying to assign String array
to String datatype. More specifically error is like this Type
mismatch: cannot convert from String[] to String
3.String array=new String[10]{}; got error why?
Wrong because you are defining an array of length 10 ([10]), then
defining an array of length String[10]{} 0
Theory above is well explained.
A PRACTICAL USE: Declare an array on the spot for a method parameter.
MyResult result = myMethod(new String[]{"value1", "value2"});
i dont quite understand by the given eg on opencsv site on how to use collection here List,eg is:
CSVReader reader = new CSVReader(new FileReader("yourfile.csv"));**
List myEntries = reader.readAll();**
I tried accessing a member of the List for eg System.out.println(myEntries.get(2)) but it gives me something like d1e604 and when i tested for existence of an element
boolean b = myEntries.contains("the element");** and it returns false.
what do i need to do to access the tokenized Strings?
by using readNext(), the elements are separated by "\n" and i want to assign the elements in a continuous no. of array.
while((tokened = reader.readNext()) != null){
int numOfArray = tokened.length;
System.out.println("number of items:"+ numOfArray) ;
for (int i = 0;i < numOfArray;i++) {
System.out.println(" tokenNo[" + i + "]: " + tokened[i]);
}
}
I think you missed a little fact about CSV. CSV is about lines AND columns. readNext() returns an array of strings representing a line. So I would guess, readAll() returns a list of string[].
Each element of your List myEntries is a String[].
i.e. That is an array of String.
that means you need a cast.
String[] entry = (String[]) myEntries.get(2);
Also -
System.out.println(myEntries.get(2)) but it gives me something like d1e604.
That's because the toString method is not properly overridden. That's the default behavior of the toString method as implemented in the Object class.
In my application i got string values dynamically. I want to assign these values to string array then print those values.But it shows an error(Null pointer exception)
EX:
String[] content = null;
for (int s = 0; s < lst.getLength(); s++) {
String st1 = null;
org.w3c.dom.Node nd = lst.item(s);
if (nd.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
NamedNodeMap nnm = nd.getAttributes();
for (int i = 0; i < 1; i++) {
st1 = ((org.w3c.dom.Node) nnm.item(i)).getNodeValue().toString();
}
}
content[s] = st1;
//HERE it shows null pointer Exception.
}
Thanks
This is because your string array is null. String[] content=null;
You declare your array as null and then try to assign values in it and that's why it is showing NPE.
You can try giving initial size to your string array or better to use ArrayList<String>.
ie:
String[] content = new String[10]; //--- You must know the size or array out of bound will be thrown.
Better if you use arrayList like
List<String> content = new ArrayList<String>(); //-- no need worry about size.
For list use add(value) method to add new values in list and use foreach loop to print the content of list.
Use ArrayList or Vector for creating collection (or array) of strings in a dynamic fashion.
List<String> contents = new ArrayList<String>();
Node node = (org.w3c.dom.Node) nnm.item(i)).getNodeValue();
if (null != node)
contents.add(node.toString());
Outside the loop you can do as follows
for(String content : contents) {
System.out.println(content) // since you wanted to print them out
It's a little hard to understand what you're after because your example got munged. However, your String array is null. You need to initialize it, not just declare it. Have you considered using an ArrayList instead? Arrays in java are fixed length (unless they changed this since my university days).
ArrayList is a lot simpler to work with.
E.g.:
List<String> content = new ArrayList<String>();
for (int i = 0; i < limit; i++){
String toAdd;
//do some stuff to get a value into toAdd
content.add(toAdd)
}
There's also something weird with one of your for loops.
for(int i=0;i<1;i++)
The above will only ever iterate once. To clarify:
for(int i=0;i<1;i++){
System.out.println("hello");
}
is functionally identical to:
System.out.println("hello");
They both print out "hello" once, adn that's it.
Use
content[s] = new String(st1);
Now it creates new instance for that particular array index.