I have stored data in a List<String[]> and need to store those data into an another String array using a loop. I have created a String array (value) and stored data in there but the issue is first element is getting replaced by second inside the loop and it will show only the last element at the end of the loop.
CSVReader reader = new CSVReader(new FileReader(csvfile));
List<String[]> data = reader.readAll();
String[] values = new String[5];
for (int i = 1; i < 5; i++) {
values = data.get(i);
System.out.println(values[1]); // data is getting replaced here
}
System.out.println(values[1]); // this will show only the last stored value
Lists are 0 indexed so unless you intentionally want to skip the first element then don't start the loop iteration at 1 rather at 0.
Yes, when performing the last println after the loop only data related to the last String[] is shown because at each iteration you're updating values i.e. values = data.get(i); to store the current String[] hence the aforementioned outcome.
You probably want a String[][] as opposed to String[] because each String[] represents a line of the file.
Thus, assuming you only want to get the first five lines from data you can do it as:
String[][] lines = data.subList(0, 5).toArray(String[][]::new);
or for all the lines read:
String[][] lines = reader.readAll().toArray(String[][]::new);
and you can test it with:
System.out.println(Arrays.deepToString(lines));
// generating data
List<String[]> data =
Stream.iterate(0, n -> n + 1)
.limit(10)
.map(i -> new String[]{"a" + i, "b" + i, "c" + i, "d" + i, "e" + i, "f" + i})
.collect(Collectors.toList());
String[][] values = new String[data.size()][];
// copy the data
for (int i = 0; i < data.size(); i++)
{
values[i] = data.get(i).clone();
}
//print the result
Arrays.stream(values).map(Arrays::toString).forEach(System.out::println);
Replace :
for (int i = 1; i < 5; i++) {
values = data.get(i);
System.out.println(values[1]); // data is getting replaced here}
With:
for (int i = 0; i < 5; i++) {
values = data.get(i);
System.out.println(values[1]); // data is getting replaced here}
I think you have a little error inside the for loop. Try this:
CSVReader reader = new CSVReader(new FileReader(csvfile));
List<String[]> data = reader.readAll();
String[] values = new String[5];
for (int i = 1; i < 5; i++) {
values[i] = data.get(i);
System.out.println(values[1]); // data is getting replaced here
}
System.out.println(values[1]); // this will show only the last stored value
I think you are missing the "[i]" at the first line inside the for loop.
Your data variable contains a list of String[] (string arrays). Your for loop is attempting to store them in values which is a single String[].
Depending on what you are trying to do, you can do as the comments suggest and make a 2D String array. However, the fact that you want to remove them from a perfectly good list of String[]'s leads me to believe you probably want them in one big String[].
Below is an example of how to put the first N (in this case 5) words you parse from the csv into the values variable. However, we would be able to give you better guidance if you provided what the ultimate use case of your code snippet is.
// initialize test data
List<String[]> data = new ArrayList<String[]>();
String[] a = {"a1", "a2"};
String[] b = {"b1", "b2"};
String[] c = {"c1", "c2"};
data.add(a);
data.add(b);
data.add(c);
// big N is how many words you want
int N = 5;
// little n tracks how many words have been collected
int n = 0;
String[] values = new String[N];
// loop through csv collect
for (int i = 0; i < data.size(); i++){
String[] cur = data.get(i);
// loop through the strings in each list entry
for (int j = 0; j < cur.length; j++){
// store value and increment counter
values[n] = cur[j];
n++;
// stop if maximum words have been reached
if (n >= N)
break;
}
// stop if maximum words have been reached
if (n >= N)
break;
}
for (int i = 0; i < values.length; i++)
System.out.println(values[i]);
Related
How can I remove the item in an array that is selected by the random?.
Instead of giving me two different items in an array it's just printing the same item selected by the random.
String[] names = {"jey","abby","alyssa","cole","yzabel","miho"};
Random rand = new Random();
String names_rand = names[rand.nextInt(names.length)];
for(int i = 0; i < 2; i++){
System.out.println(names_rand);
}
It's simply because any code outside the for loop won't run again, try this to run the random code every loop to get a new (possible same since it's random) string from the array
String[] names = {"jey","abby","alyssa","cole","yzabel","miho"};
Random rand = new Random();
for(int i = 0; i < 2; i++){
String names_rand = names[rand.nextInt(names.length)];
System.out.println(names_rand);
}
as for deleting the item that would be somehow complicated using a string array as once it's allocated you can't add or delete from it (you can't modify it's size )unless you are willing to make a new temporary array, copy all of its items without the chosen string like this maybe :
String[] names = {"jey", "abby", "alyssa", "cole", "yzabel", "miho"};
Random rand = new Random();
for (int i = 0; i < Math.min(2, names.length); i++) {
int randInt = rand.nextInt(names.length), cpyIdx = 0;
String[] namesTemp = new String[names.length - 1];
for (int j = 0; j < names.length; j++) {
if (j != randInt) {
namesTemp[cpyIdx] = names[j];
cpyIdx++;
}
}
names = namesTemp;
a better version of this complicated code would be using an ArrayList, which allows to add and remove its items (change its size at runtime) easily with just one method call like this :
ArrayList<String> names = new ArrayList<>(Arrays.asList("jey", "abby", "alyssa", "cole", "yzabel", "miho"));
Random rand = new Random();
for (int i = 0; i < Math.min(2, names.size()); i++) {
int randInt = rand.nextInt(names.size());
names.remove(randInt);
}
you can read more about ArrayLists how to add/remove items through this link as well as many tutorials out there just write ArrayList java in google search engine
N.B : I've added Math.min(2, names.length) to the for loop condition as I was afraid you would get to the case that the array length would be less than the number of items you want to delete, using Math.min I'm ensuring that the for loop won't try access an item that isn't there in the array
If you are required to use Arrays then this way is probably among the best
with the limitations involved.
generate a random number and get the name
create a new temporary array to hold the all names less the one removed.
copy all names up to but excluding the one removed to the temp array
copy all names just after the one excluded to the temp array.
assign the temp array to the original array
normal exceptions will be thrown if a null or empty array is used.
Random r = new Random();
String[] names =
{ "jey", "abby", "alyssa", "cole", "yzabel", "miho" };
ArrayList<Integer> a;
int idx = r.nextInt(names.length);
String name = names[idx];
String[] temp = new String[names.length - 1];
for (int i = 0; i < idx; i++) {
temp[i] = names[i];
}
for (int i = idx; i < temp.length; i++) {
temp[i] = names[i + 1];
}
names = temp;
System.out.printf("'%s' was removed.%n",name);
System.out.println(Arrays.toString(names));
Prints something like
'jey' has been removed.
[abby, alyssa, cole, yzabel, miho]
It's interesting to note that the best way would be to use an ArrayList as already given in a previous answer. But the primary reason is that an ArrayList does not need to make a temporary array but simply copies in place. Then it adjusts the size value, effectively hiding the garbage still in the internal array.
I have created an app which will find the common factors of 2 or more numbers entered by the user. I have used a single Edit Text field to get user input. Different numbers are separated by comma (,). All the numbers are stored in an array.
My question is that how can I access the elements of the array of n size. Following is the code. I want to find the factors of all the user entered numbers. I can find the the factors of integernumbers[0] index but after that the code thorws ArrayIndexOutOfBoundsException.
int factors1 = 0;
int factors12 = 0;
StringBuilder sb = new StringBuilder();
String value = edtCommonFact.getText().toString()
String[] stringsNumber = value.split(",");
Integer[] integersNumbers = new Integer[stringsNumber.length];
for (int i = 0; i<stringsNumber.length; i++){
integersNumbers[i] = Integer.parseInt(stringsNumber[i]);
}
Arrays.sort(integersNumbers);
for (int i = 1; i<=integersNumbers[0]; i++){
if (integersNumbers[0]%i == 0){
factors1 = i;
sb.append(factors1).append(" ");
for (int j = 1; j<=integersNumbers.length; j++){
if (integersNumbers[j]%j == 0){
factors12 = j;
sb.append(factors12).append(" ");
}
}
}
}
String result = sb.toString();
commonFactResult.setText("Common factors are: " + result);
Thanks in Advance
You can use ArrayList because not like an array it doesn't need a size declaration. As an example if we wants an String array with size 10 we need to declare it as
String[] s = new String[10]
but in ArrayLists you can define the ArrayList and use it for any no of items.
List<String> s = new ArrayList<>()
i'm trying to read a line in a file and store it in an array, after doing this i want to remove the first element in the array so that the length can be 1 element less and make the length of the array same as another array so i can match both arrays using for loop. the line i want to read from the file is
"London 2 7 24 16 -15 8 27"
try {
File myObj = new File("temperatures.txt");
FileReader read = new FileReader(myObj);
Scanner myReader = new Scanner(myObj);
Scanner input = new Scanner(System.in);
LineNumberReader lines = new LineNumberReader(read);
lines.skip(Long.MAX_VALUE);
int len = lines.getLineNumber();
int count = len;
String ans;
for (int i = 0; i < len && myReader.hasNextLine();i++){
System.out.println(count+" Cities temperature left!");
System.out.print("Do you want to check temperature details; enter y or n: ");
ans = input.nextLine();
if(ans.equals("y")){
String[] getData = myReader.nextLine().split(" ");
String[] days = {"Mon", "Tue", "Weds", "Thurs", "Fri", "Sat", "Sun"};
for (int j = 0; j < getData.length; j++){
System.out.println(days[j]+": "+getData[j]);
}
}
else{
}
}
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
There are several possible solutions to your problem.
Not deleting the element at all
You can iterate 2 arrays in parallel like this:
for (int j = 0; j < days.length; j++) {
System.out.println(days[j] + ": " + getData[j + 1]);
}
As you can see, we start and index 0 with days, but we start at 1 with getData. This will work, because you know that getData is exactly one element bigger than days. Also, note that the condition of the loop changed to j < days.length. This is because days is shorter and so we should iterate through the shorter array. Alternatively, you can write j < getData.length - 1.
Creating a copy
There is no way to delete an element from an array. You have to construct a new array.
String[] newData = new String[getData.length - 1];
for (int j = 0; j < newData.length; j++) {
newData[j] = getData[j + 1];
}
Then you can use newData instead of getData to print the numbers.
Use a collection or a stream
I won't go into the details, but you can construct a collection (e.g. an ArrayList) from your array, delete the first element from the list (because unlike arrays, you can actually delete elements of lists), and then iterate the list (no need to create another array). Or, you can create a stream from an array, skip the first element (streams have the skip method), and copy the stream into an array.
But as for me, this way is overkill for such a simple task. I think that even creating a copy is a bit too much. You're better off just using the first solution, it's the easiest one.
Why not add +1 to the index value of getData[] in the loop?
System.out.println(days[j] + ": " +getData[j+1]);
https://drive.google.com/a/navasotaisd.org/file/d/0B3eMFMufj6uVaVNpR0JYNnV4OTQ/view
Okay, so the problem above asks that you read in a file with a message and, using and x, y coordinate system, find the characters being read in and print out the character of that index value. I honestly have tried multiple solutions with making and array of arraylists, a arraylist of arraylists and many other failed data structures. All I need to know, is how would go about reading in the message so that I can search for it?
File f = new File("cipher.in");
f.createNewFile();
Scanner scan = new Scanner(f);
int numOfLines = scan.nextInt();
scan.nextLine();
ArrayList<Character> list = new ArrayList();
String code = "";
for (int i = 0; i < numOfLines; i++) {
code = scan.nextLine();
for (int j = 0; j < code.length(); j++) {
list.add(code.charAt(j));
}
}
int index = 0;
char[][] matrix = new char[(int)(list.size())][(int)(list.size())];
for (int r = 0; r < matrix.length; r++) {
for (int c = 0; c < matrix[r].length; c++) {
matrix[r][c] = list.get(index);
index++;
if(index>=list.size())
index--;
}
}
Sorry if this problem is a bit long. It's for my class I need to turn this problem in to be able to make a 100 in the gradebook. I'm just utterly stuck and frustrated.
Try to use a hash table to store the data. You will be able to search for it later on.
The key fits quite nicely into a two-dimensional charcter array (char[][]). I would consider reading the first line (which specifies the number of lines on the key (rows of the array), and then construct the array. You have a constraint defined that a row can be no longer than 100 characters long so you can now define the complete "map".
After that i would read each line of the key, use an operator as charAt(index) and fill the map.
From there you have a very convenient structure to lookup the messages in the next part of the assignment.
Try this out , this is you code with changes and comments so that you can understand the changes and the way this code works based on the instruction in your link, I did not try to compile it, so if it has any compilation errors try to fix them. I kept your code and commented out the items that are not needed so that you can look at the differences,
File f = new File("cipher.in");
//f.createNewFile(); //* you are overwriting the file here
Scanner scan = new Scanner(f);
int numOfLines = scan.nextInt();
//str = scan.nextLine(); //* you just skipped one line from the numOfLInes
//ArrayList<Character> list = new ArrayList(); //* this does not help, you need to index into the line number, char index
TreeMap charMap = new TreeMap(); //* use this to map the line number to a char array
String code = "";
for (int i = 0; i < numOfLines; i++) {
strubg code = scan.nextLine();
charMap.put(i, code.toCharArray()); //* map the line number with the char array of each line
//for (int j = 0; j < code.length(); j++) {
// list.add(code.charAt(j));
//}
}
int numOfMessageLines = scan.nextInt(); //* get the number of message lines next
for (int i = 0; i < numOfMessageLines; i++) {
string str = scan.nextLine();
string[] pairs = str.split(" "); //* each line has several key pairs for line number char number seprated by spaces
ArrayList<char> list = new ArrayList(); //* this does not help, you need to index into the line number, char index
for(int j=0; j<pairs.length; j++)
{
string[] st = pairs[j].trim().split(","); //* example 2,13 indicate line 2 character 13 non zero indexed
int lineNum = Integer.parse(st[0]) - 1; //* zero indexed line number since we stored the lines in zero index map
int charNum = Integer.parse(st[1]) - 1; //* zero indexed char number since we stored the char array in zero indexed array
char[] chars = charMap.get(lineNum); //* get the char array for this line number
char c = chars[charNum]; //* get the character for the first message
list.add(c);
}
String message = new String(list.toArray()); //* construct the message from the char array
System.out.println(message);
}
//int index = 0;
//char[][] matrix = new char[(int)(list.size())][(int)(list.size())];
//for (int r = 0; r < matrix.length; r++) {
// for (int c = 0; c < matrix[r].length; c++) {
// matrix[r][c] = list.get(index);
// index++;
// if(index>=list.size())
// index--;
// }
//}
I am using this code to insert the details in to TwoDimensional Array. But while retrieving the data from the array the first element value changes to null.
Cursor consultancy = db.getConsultancy(this);
if(consultancy!=null)
{
consultancy.moveToFirst();
consultancy.moveToNext();
consultancynames = new String[(int) db.getConsultancyCount()-1];
for(int i=0;i<db.getConsultancyCount()-1;i++)
{
consultancynames[i] = consultancy.getString(2);
int consultantid = Integer.parseInt(consultancy.getString(consultancy.getColumnIndex(TimeAndExpensesLocalDB.CT_CONSULTANCYID)));
Cursor project_namecur = db.getProjectCode(this, consultantid);
if(project_namecur!=null)
{
project_namecur.moveToFirst();
projectname = new String[(int) db.getConsultancyCount()][project_namecur.getCount()];
for(int j=0;j<project_namecur.getCount();j++)
{
projectname[i][j] = project_namecur.getString(3);
project_namecur.moveToNext();
}
}
consultancy.moveToNext();
}
}
//... Print array
for (int i =0; i < consultancynames.length; i++) {
for (int j = 0; j < projectname.length; j++) {
System.out.print(" " + projectname[i][j]);
}
System.out.println("");
}
Output
05-25 12:58:22.700: I/System.out(2373): null null null
05-25 12:58:22.700: I/System.out(2373): Other-1 Other-2 Other-3
I am not sure what is happening.
Thanks for your help guys..
You're creating a new array on each iteration of the loop:
projectname = new String[(int) db.getConsultancyCount()][project_namecur.getCount()];
So on the first iteration you're creating an array and filling in the first "row" of the array. On the second iteration you're creating a new array (which will default to having null elements) and filling in the second row.
I suspect you need to allocate the "outer" array once before the loop, then allocate the "inner" array based on how many project names there are for that consultant:
// Note: more idiomatic names would be consultancyNames and
// projectNames. It's also unclear why you're subtracting one from the count...
consultancynames = new String[(int) db.getConsultancyCount() - 1];
projectnames = new String[consultancynames.length][];
for (int i = 0;i< consultancenames.length; i++) {
...
projectnames[i] = new String[project_namecur.getCount())];
...
}
Then you'll need to change your display code too, e.g. to
for (int i =0; i < projectname.length; i++) {
for (int j = 0; j < projectname[i].length; j++) {
System.out.print(" " + projectname[i][j]);
}
System.out.println("");
}
Note that you can't do the following:
projectname = new String[(int) db.getConsultancyCount()][project_namecur.getCount()];
for(int j=0;j<project_namecur.getCount();j++)
{
projectname[i][j] = project_namecur.getString(3);
project_namecur.moveToNext();
}
Here's why:
After the first line projectname will be an array of arrays.
Since the arrays are object references you have an array of object references.
Since the default value of an object reference is null, you'll have an array of null elements.
This means you can't do
projectname[i][j] = project_namecur.getString(3);
since it corresponds to
String[] row = projectname[i];
// row == null !
row[j] = project_namecur.getString(3);