How to create an object dynamically from a string array? - java
I have a String array in C# like below:
String[] myArray = {"1","Jack","18","2","John","22","3","Mark","29"}
Actually there are 3 objects in my array, first column is ID, second is Name and third is Age. So I need to insert 3 rows into my SQL table, each represents one person.
What is the best way to handle it?
I try:
Person p = new Person();
for (int i = 0; i <= myArray.Length; i++)
{
if (i==0) p.Id = myArray[i];
if (i==1) p.Name = myArray[i];
if (i==2) p.Age = myArray[i];
if (i%3==0) AddNewRecord(p);
}
But then how can I remove the first object from my array and start from 0 again?
Thanks.
PS. Couldn't find a proper title for my issue, sorry, appreciate if you may edit.
Edit: Java or C# answer, both fine by me
You only take the first three values to create a Person object and then call AddNewRecord every 3rd iteration. Instead, every 3rd iteration you will need to set p to a new Person in order to prevent mutating the existing Person object already used to invoke AddNewRecord. To avoid only using the 3 first array elements, you want to % 3 on them too. 0 % 3 = 0, 1 % 3 = 1, 2 % 3 = 2, 3 % 3 = 0. Any number % 3 will tell you whether you're on the ID, Name or Age.
I think it's worth asking why you have an array of strings containing object data. Why not create the Person before putting all of their info in an array to avoid this problem?
try below code this is worked you expected
for (int i = 0; i <= myArray.Length; i++)
{
if (i == 0) p.ID = myArray[i];
if (i == 1) p.Name = myArray[i];
if (i == 2) p.Age = myArray[i];
if (i!=0 && i % 2 == 0)
{
if (myArray.Length > 0)
{
myArray = myArray.Skip(3).ToArray();
}
i = 0;
}
}
Related
JAVA - Not able to properly fill multidimentional array from another array
I have a string of values separated by commas that I converted into an array, which I was then going to use to create a 2D array. When creating a loop to add the data from the first array to the 2D array it is repeating the data. The output I'm getting is: 4428,40,401,610,2016,3821,31,347,572,2015,4381,38,341,520,2014,2536,17,193,290,2013,4295,39,371,552,2012,4643,45,343,502,2011,3922,28,312,475,2010,4434,30,350,541,2009,4038,28,341,536,2008,218,1,20,28,2007,46,0,6,15,2006,65,0,9,16,2005,4428,40,401,610,2016,3821,31,347,572,2015,4381,38,341,520,2014,2536,17,193,290,2013,4295,39,371,552,2012,4643,45,343,502,2011,3922,28,312,475,2010,4434,30,350,541,2009,4038,28,341,536,2008,218,1,20,28,2007,46,0,6,15,2006,65,0,9,16,2005,4428,40,401,610,2016,3821,31,347,572,2015,4381,38,341,520,2014,2536,17,193,290,2013,4295,39,371,552,2012,4643,45,343,502,2011,3922,28,312,475,2010,4434,30,350,541,2009,4038,28,341,536,2008,218,1,20,28,2007,46,0,6,15,2006,65,0,9,16,2005,4428,40,401,610,2016,3821,31,347,572,2015,4381,38,341,520,2014,2536,17,193,290,2013,4295,39,371,552,2012,4643,45,343,502,2011,3922,28,312,475,2010,4434,30,350,541,2009,4038,28,341,536,2008,218,1,20,28,2007,46,0,6,15,2006,65,0,9,16,2005,4428,40,401,610,2016,3821,31,347,572,2015,4381,38,341,520,2014,2536,17,193,290,2013,4295,39,371,552,2012,4643,45,343,502,2011,3922,28,312,475,2010,4434,30,350,541,2009,4038,28,341,536,2008,218,1,20,28,2007,46,0,6,15,2006,65,0,9,16,2005 and the correct output should be: 4428,40,401,610,2016,3821,31,347,572,2015,4381,38,341,520,2014,2536,17,193,290,2013,4295,39,371,552,2012,4643,45,343,502,2011,3922,28,312,475,2010,4434,30,350,541,2009,4038,28,341,536,2008,218,1,20,28,2007,46,0,6,15,2006,65,0,9,16,2005 Expected results: {{4428,40,401,610,2016} {3821,31,347,572,2015} {4381,38,341,520,2014} ...} and so on, every 5 My code for adding the array to the 2D array is below: {String[] columns = {"Yards","Touchdowns","Attempts","Incompletions","Year"}; String[] data1 = results1.split(","); Object [][] data11 = new Object[columns.length][data1.length]; for(int i = 0; i<columns.length;i++){ for(int j = 0; j<data1.length;j++){ data11[i][j] = data1[j]; //System.out.print(data11[i][j]+","); } }} EDIT: Solution! Object [][] data11 = new Object[data1.length/columns.length][columns.length]; int column = -1; for(int j = 0; j<data1.length;j++){ if(j % columns.length == 0) column = column+1; data11[column][j % 5] = data1[j]; }
Maybe this work for you: Object [][] data11 = new Object[columns.length][data1.length / 5]; int column = -1; for(int j = 0; j<data1.length;j++){ if(j % 5 == 0) column = column + 1 data11[j % 5][column] = data1[j]; } Note the matrix size changed and the assignation too. Haven't tried, probably you can make a prettier version. Hope it helps!
You also loop the first array (i), so he will repeat it. Just write this: data11[0][j] = data1[j]; Or even don't do the first loop at all, depending on what you need. Assuming your output, you only want to fill in the first position (0) of the array.
How to remove object from array
Please bear within as it might be difficult to understand I have an array of jbuttons 50 size big, for this example ill use 7 I have jbutton object within 1 2 3 4 6 7 but not 5. These are printed on the screen. I want to remove these jbuttons however all buttons up to 5 are removed while the last two are not. for(int i = 1; i < 51; i++){ if(seat.buttonArray[i] == null){ remove(seat.buttonArray[i]); seat.buttonArray[i] = null;} }
There is no way to remove element from array, assuming you want latter indexes changed after remove. For this purpose, you should use List: Iterator buttonIterator = seat.buttonList.iterator(); while (buttonIterator.hasNext()) { Object button = buttonIterator.next(); //or more specific type, if your list was generified if (button == null) { //or some other criteria, wrote this just as an example buttonIterator.remove(); } } If using array is mandatory, you have two options: Set seat.buttonArray[i] to null value, indicating it has been removed; Recreate array each time you deleted something. See System.arraycopy javadoc for details, although I do not recommend this approach because of performance considerations.
You could store the values in a temp array and then copy what you want back into your original array. Somewhat similar to this: int myArray[50]; int temp[50]; int good; for (int i = 0; i < 50; i++) { myArray[i] = i; } for (int i = 0; i < 50; i++) { temp[i] = myArray[i]; } good = 0; for (int i = 0; i < 50; i++) { if (i < 10) { } else { myArray[good] = temp[i]; good += 1; } } Looks messier than I first thought... But it essentially does what you're wanting.
Get the missing digits of an array
I have an array with digits and that array is not sorted. The user is able to delete numbers from the array. But the user should be able to add the digit later. Basically I want to write in a database the id. The user is able to remove rows but if he add a row the id should be a missing digit from a deleted row. At the moment I solve it like that: for (Object[] object : data) { if ((int) object[1] > id) { id = (int) object[1]; } } But with that I only get the largest number and not the missing number. How I am able to get a missing number? Example: 4, 2, 3, 1 the user deletes row 2 and row 4 so I have 3, 1 now I want to calculate or with if statements whatever to get the 2 and, if the user add a another row the, 4 back. Keep in mind that the user could close the program, so it is not possible to save the numbers in a other array! Thank you for help
From your example, sum the numbers from the beginning to the end, 1+2+3+4 = 10 and subtract the sum of the numbers you have, 1+2+4 = 7 So 10 - 7 = 3 (the missing number) ----------------------------------------------------EDIT ---------------- how about this? public class SandBox7 { public static void main(String[] args) { Integer[] array = new Integer[] { 1, 4, 9 }; SandBox7 s = new SandBox7(); List<Integer> mis = s.getMissingNumbers(array); } public List<Integer> getMissingNumbers(Integer[] in) { int max = getMaximum(in); // System.out.println(max); List<Integer> numbers = Arrays.asList(in); ArrayList<Integer> missing = new ArrayList<>(); for (int i = 1; i < max; i++) { if (!numbers.contains(i)) { missing.add(i); } } return missing; } private int getMaximum(Integer[] in) { int tmp = -1; for (int i = 0; i < in.length; i++) { if (tmp < in[i]) tmp = in[i]; } return tmp; } }
Look at below code..might be helpful int data[]={1,2,4}; int i=1; for(Object object : data){ if((Integer)object!=i++) break; } System.out.println(i-1);//This will print 3.
One approach could be maintaining a parallel array which will contain the deleted number. Object[] data = ...; Object[] delData = ...; So every time you insert/add a new number you need to check that number exists in parallel array or not.
You have some possibilities, and it is a design problem you have to decide yourself. Just some alternatives: Best: renumber IDs on deletion, but needs meta information on referencing foreign keys. If the data is ordered by ID. The numbers of deletions when not renumbered: int deletions = data.length - (data.length == 0 ? 0 : data[data.length - 1][1]); With a binary search, you can find a deleted hole (shifted number). Unordered. Keep the number of deletions maybe. Keep an unbounded BitSet of data.length bits. Or alternatively a Set<Integer> with deletions. And renumber when the set becomes too large. (A set of ranges from-ID upto to-ID would be better.)
If you sort the id's in a temporary storage so it would be simple to find the first missing number; int arr[] = {0,1,2,5}; //think you've the sorted array now int missing = arr.length; //would have the last id+1 if there is no missing id for (int i = 0; i < arr.length; i++) { if (i != arr[i]) { missing = i; break; } } System.out.println(missing); //3 will be printed.
Count The Amount Of Data In An Array Including SOME Null
I'm coding in java and I need to create a function that returns the number of data objects that are currently in an ArrayList. At the moment I have this: int count = 0; for (int i = 0; i < data.length; i++) { if (data[i] != null) { count ++; } } return count; But the problem is that an array list that includes null data is acceptable, and I have to count their null data towards this counter. How do I include the null data that's in the middle of this array, and not the null data that's not supposed to be counted for? For example, I have some tester code that adds (8),null,null,(23),(25) to the array, and this function should return 5 when the initial array size is 10.
I'm going to assume you're using a regular array (your question is somewhat ambiguous about this). Traverse through the array backwards until you find a non-null element: public static int count(Object[] a) { int i = a.length - 1; for (; i >= 0 ; i--) if (a[i] != null) break; return i + 1; } You could also have public static <T> int count(T[] a) { int i = a.length - 1; for (; i >= 0 ; i--) if (a[i] != null) break; return i + 1; } Let's test it out, using an example analogous to the one you provided: Object[] a = new Object[10]; a[0] = new Object(); a[3] = new Object(); a[4] = new Object(); System.out.println(count(a)); Output: 5
You will need two separate counters. The first one will count normally. The second one starts counting when you find null data. Then when you find a non-null data, just add the second counter to the first one and continue counting with the first counter until you find a null again.
int count = 0; for (int i = data.length - 1; i >= 0; i--) if (data[i] != null || count > 0) count += 1; return count; At least that's how I understood your requirements - count nulls, except for trailing nulls. But maybe that's not actually what you meant? Edit Unless you're actually using ArrayList (as Jon was asking), where .size() is different from capacity and will count all added elements (including nulls). You can't actually even get the capacity from an ArrayList.
Finding pairs out of five
I am having trouble finding pairs in a string of size five. So therefore, there can only be two pairs. For every pair that I have found, I should increase the score by 2 points. Here is what I have so far, but it is incorrect. String temp = "4 5 4 3 3"; String tempLine = temp.replaceAll(" ", ""); String[] hand = temp.split(" "); for(int i = 0; i < hand.length; i++) { if(hand[i].equals(tempLine.substring(0, 1)) && i !=0 ) score += 1; if(hand[i].equals(tempLine.substring(1, 2)) && i != 1 ) score += 1; if(hand[i].equals(tempLine.substring(2, 3)) && i!= 2 ) score += 1; if(hand[i].equals(tempLine.substring(3, 4)) && i!= 3) score += 1; if(hand[i].equals(tempLine.substring(4)) && i != 4) score += 1; } EDIT: I am trying to find pairs in the hand that have similar value, for example 4 would be one pair found in this hand
Sort the hand first and then loop though looking for hand[i] == hand[i-1]. Note that you might have to be slightly clever as to not count sets of 3s or 4s twice but this should get you started.
Create an actual Hand class and don't use Strings to represent your cards. A Card's rank and suit are suitable candidates for an enum: class Card { enum Suite { ... }; enum Rank { ... }; private final Suite s; private final Rank r; // ... } class Hand { private Card[] cards; // ... } And sort the Card[] in your Hand class which makes it easier to evaluate . Checkout Oracle's enum tutorial which has an example with cards: http://download.oracle.com/javase/1.5.0/docs/guide/language/enums.html
I think this fits what you're trying to do. char[] hand = {'a','b','c','b','c'}; /* sort the hand to ensure pairs are next to each other */ for(int x=0;x<hand.length - 1;x++){ for(int y=(x+1);y<hand.length;y++){ if((int)hand[x] > (int)hand[y]){ char temp = hand[y]; hand[y] = hand[x]; hand[x] = temp; } } } int score = 0; for(int x=0;x<hand.length - 1;x++){ if(hand[x] == hand[x + 1]){ score++; /*if you want to make sure you only get pairs add an "x++;" that way it'll skip over the letter you just tested*/ } }
1) Why aren't you comparing elements of the hand array to other elements? You already did the work to interpret the string and create the array data; use it. 2) There are more possible pairs of elements than that. Put down five similar objects in a row in front of you at the computer and try it out for yourself. You should be able to identify ten pairs. You should also be able to identify a pattern to how to find/label the pairs.
This example below is one possibility of how to count pairs. The question is how it should behave (increase the score) in case there are three equal values in the string or array or whatever. Shall this be counted as three pairs or not at all...? 123 is in fact three combinations 12 && 13 && 23 111 is in fact three combinations 11 && 11 && 11 package edu.harris.pairs; public class FindPairs { public static void main(String[] args) { String s = "hello"; int score = 0; for (int i = 0; i < s.length() - 1; i++) { for (int j = i + 1; j < s.length(); j++) { if (s.charAt(i) == s.charAt(j)) { score++; } } } System.out.println(score); } } Hope this helps a bit.