How to add new element to the end of array in Java - java

StudentModel[] student = new StudentModel[] {
new StudentModel(1, "Kanha", "Vong", "Female", "09/09/2000", "Siem Reap", "016663332"),
new StudentModel(2, "Echrysa", "Chhy", "Male", "01/20/2000", "Pursat", "097222444"),
new StudentModel(3, "Sopheak", "Chok", "female", "29/06/2005", "Battambang", "096565544"),
new StudentModel(4, "Sakda", "Heang", "Male", "04/12/2001", "Banteay Meanchey", "097889900"),
new StudentModel(5, "TongHan", "Khy", "Male", "03/06/2002", "Pursat", "0976543201"),
new StudentModel(6, "Seyma", "Hor", "Female", "27/08/2004", "Battambang", "015765456")
};
public void insertStudent(StudentModel[] student){
int n = student.length;
student = new StudentModel[n+1];
System.out.print("Enter Student ID:");
student[n].setId(sc.nextInt());
System.out.print("Enter First Name:");
student[n].setFirstName(sc.nextLine());
.......................................
}
I've got error message: Cannot invoke "StudentModel.setId(int)"
because "student[n]" is null. Anyone can help to fix this? Thank you!

Are you depended on Arrays?
If not you could use Map with List or two Lists. My guess:
privat Map<int,List<String>> students = new HashMap<int, List<String>>();
public void addStudent(int id,String name, String lastName, String birthdate,...){
List<String> student = new LinkedList<String>(); //LinkedList for fixed order
student.add(name);
student.add(lastName);
student.add(birthdate);
students.put(id, student);
}
Should work like this and with LinkedList the order is fixed and you can get the data by knowing the index if needed
Otherwise you could try a List in a List.
Advantage here ist that you can easy access the data of the students by index and good methods!

Maybe try this
String[] test = new String[]{"Test1", "Test2"};
//try new on
String[] tester = new String[test.length + 1];
for(int i = 0; i < test.length; i++){
tester[i] = test[i];
}
// -1 cause of index 0 to length - 1
tester[tester.length - 1] = "Test3";
test = tester;
for(String text : test){
System.out.println(text);
}
worked fine for me

Related

How to add items to a list of lists

I aim to print a list of lists containing entry and exit times in the 24 hour decimal format from the "AM"-"PM" String format input by the user as a String array like this:
{6AM#8AM, 11AM#1PM, 7AM#8PM, 7AM#8AM, 10AM#12PM, 12PM#4PM, 1PM#4PM, 8AM#9AM}
I declared the individual lists inside the for loop and assigned them values inside the loop but got the following run time exception from my code:
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
Kindly help me debug my code:
import java.util.*;
public class TimeSchedule
{
public static List<List<Integer>> Timein24hourFormat(String[] input1)
{
List<List<Integer>> scheduledTime = new ArrayList<List<Integer>>();
int [] exitTime = new int[input1.length];
int [] entryTime = new int[input1.length];
for (int i=0;i<input1.length;i++)
{
List<String> listOfStrings = new ArrayList<>();
List<Integer> tempList = scheduledTime.get(i);
String[] timeSlot = input1[i].split("#");
for (int m=0;m<2;m++)
{
listOfStrings.add(timeSlot[m]);
if (listOfStrings.contains("AM"))
{
listOfStrings.remove("AM");
tempList.add(Integer.parseInt(listOfStrings.get(m)));
}
if (listOfStrings.contains("PM") && timeSlot[m].contains("12"))
{
listOfStrings.remove("PM");
tempList.add(Integer.parseInt(listOfStrings.get(m)));
}
if (listOfStrings.contains("PM") && !timeSlot[m].contains("12"))
{
listOfStrings.remove("PM");
tempList.add((Integer.parseInt(listOfStrings.get(m))) + 12);
}
}
}
return scheduledTime;
}
public static void main (String[]args)
{
Scanner input = new Scanner(System.in);
int customersNumber = input.nextInt();
input.nextLine();
String [] entryExitTime = new String[customersNumber];
for (int i=0;i<customersNumber;i++)
{
entryExitTime[i] = input.nextLine();
}
System.out.println(Timein24hourFormat(entryExitTime));
}
}
public static List<List<Integer>> Timein24hourFormat(String[] input1)
{
List<List<Integer>> scheduledTime = new ArrayList<List<Integer>>();
int [] exitTime = new int[input1.length];
int [] entryTime = new int[input1.length];
for (int i=0;i<input1.length;i++)
{
List<String> listOfStrings = new ArrayList<>();
List<Integer> tempList = scheduledTime.get(i);
String[] timeSlot = input1[i].split("#");
scheduledTime is empty at this stage and that's why you can not retrieve value and you get IndexOutOfBoundsException

Create an array of objects

I'm fairly new to java, but I understand programming concepts. I'm working on a trading game. I want to be able to list every item I want in a .txt file and read down the list making an instance of Item() object for each. I know how to read the input, it's then sorting them into an array that is hard to figure out.
Is an array the right way to go for this? Or is there some other way to handle my item information?
public class Item {
File itemList = new File("Items.txt");
ArrayList<Item> Items = new ArrayList<>();
String line = "";
String name = "";
int price = 0;
int ID = 0;
public void setItem (String theName, int thePrice, int theID)
{
name = theName;
price = thePrice;
ID = theID;
}
public void Initialize () throws FileNotFoundException
{
Scanner scan = new Scanner(itemList);
do
{
do
{
line = scan.nextLine();
while (!line.startsWith("#")) {line = scan.nextLine();}
if (line.matches(".*\\d+.*"))
{
price = Integer.parseInt(line);
}else
{
name = line;
}
}while(!line.equals(""));
Items.add(new Item());
ID++;
}while (!line.equals("end"));
}
}
There are several ways you can store your items maybe the easiest way is doing it with an array list.
ArrayList<Items> items = new ArrayList<Items>();
And assuming that you create new items with your input data:
/*This goes in a loop where you read in currentInputData*/
items.add(new Item(currentInputData));
For further information about manipulating ArrayLists refer to javadoc: https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html

Java add items into class as an Array

I have simply this below class structure and I want to add any item to it.
public class Person implements Serializable {
private String name;
private String mobile;
public Person(String n, String e) { name = n; mobile = e; }
public String getName() { return name; }
public String getMobile() { return mobile; }
#Override
public String toString() { return name; }
}
I want to add any item like with this:
people = new Person[]{
new Person("Hi" , " programmer"),
new Person("Hello", " world")
};
My code is this and I want to add items into that by while() my code is don't correct.
people = new Person[]{};
while (phones.moveToNext())
{
people = new Person("Hi" , " programmer");
people = new Person("Hello", " world")
}
you have error in your source code you are trying to put Object of person into array so it will gives you compilation error
to overcome this problem first take List of Type Person and convert it into array and do your business logic on Array its better to use List instead of Array
List<Person> personlst = new ArrayList<Person>();
while (phones.moveToNext())
{
personlst.add(new Person("Hi" , " programmer"));
personlst.add(new Person("Hello", " world"));
}
Object[]arryPer = personlst.toArray();
Person[]people = new Person[arryPer.length];
for (int j = 0; j < arryPer.length; j++) {
people[j] = (Person) arryPer[j];
}
above code of block give you array of type people
You are not defining the number of elements that you want to push into array. Also you are not even making those elements to an array. You should do something like:
int i =0;
people = new Person[1000];// you need to define how many elements you need here or go for list
while (phones.moveToNext())
{
people[i++] = new Person("Hi" , " programmer");
people[i++] = new Person("Hello", " world")
}
Define first the size of your Person.
Person[] people = new Person[10];
then do your iteration for example.
for(int i = 0; i < 0; i++){
people[i] = new Person("Hi" , " programmer");
}
first put all elements in list then form the array:
List<Person> list = new ArrayList<Person>();
while (phones.moveToNext()) {
list.add(new Person("Hi", " programmer"));
list.add(new Person("Hello", " world"));
}
Person[] persons = new Person[list.size()];
list.toArray(persons);
}
Try Arrays.asList
http://www.tutorialspoint.com/java/util/arrays_aslist.html
Note - it is good only for a small number of elements as arrays generally take contiguous memory.
As people have stated above, list is any day better from space point of view.

Get value (String) of ArrayList<ArrayList<String>>(); in Java

I know it's simple question, but in
ArrayList<ArrayList<String>> collection;
ArrayList<String> listOfSomething;
collection= new ArrayList<ArrayList<String>>();
listOfSomething = new ArrayList<String>();
listOfSomething.Add("first");
listOfSomething.Add("second");
collection.Add(listOfSomething);
listOfSomething.Clear();
listOfSomething.Add("first");
collection.Add(listOfSomething);
I want to take String from ArrayList of ArrayList, and I don't know how to do that. For example I go
ArrayList<String> myList = collection.get(0);
String s = myList.get(0);
and it works! but:
Big update:
private List<S> valuesS;
private List<Z> valuesZ;
ArrayList<ArrayList<String>> listOfS;
ArrayList<String> listOfZ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Zdatasource = new ZDataSource(this);
Zdatasource.open();
valuesZ = Zdatasource.getAllZ();
Sdatasource = new SDataSource(this);
Sdatasource.open();
valuesS = Sdatasource.getAllS();
List<Map<String, String>> groupData
= new ArrayList<Map<String, String>>();
List<List<Map<String, String>>> childData
= new ArrayList<List<Map<String, String>>>();
listOfS = new ArrayList<ArrayList<String>>();
listOfZ = new ArrayList<String>();
for (S i : valuesS) { // S is class
for (Z j : valuesZ) { // Z is class
if(j.getNumerS().equals(i.getNumerS())) {
listOfZ.add(j.getNumerZ());
}
else
{
//listOfZ.add("nothing");
}
}
listOfS.add(listOfZ);
if(!listOf.isEmpty()) listOfZ.clear();
}
#Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition,
int childPosition, long id) {
try
{
ArrayList<String> myList = listOfS.get(groupPosition);
String s = myList.get(childPosition);
PrintToast("group "+Integer.toString(groupPosition)+", child "+Integer.toString(childPosition) + " , "+ s);
}
catch(Exception e)
{
Log.e("FS", e.toString());
}
return true;
}
return me java.lang.IndexOutOfBoundsException: Invalid index 1, size is 0
when I click on item which really should exist. I didn't show code which generate ListView, but I can tell you that my listOfS contains 3 items:
first is Null listOfZ, second listOfZ got 2 elements, third listOfZ got 1 element.
listOfSomething.Clear();
listOfSomething.Add("first");
collection.Add(listOfSomething);
You are clearing the list here and adding one element ("first"), the 1st reference of listOfSomething is updated as well sonce both reference the same object, so when you access the second element myList.get(1) (which does not exist anymore) you get the null.
Notice both collection.Add(listOfSomething); save two references to the same arraylist object.
You need to create two different instances for two elements:
ArrayList<ArrayList<String>> collection = new ArrayList<ArrayList<String>>();
ArrayList<String> listOfSomething1 = new ArrayList<String>();
listOfSomething1.Add("first");
listOfSomething1.Add("second");
ArrayList<String> listOfSomething2 = new ArrayList<String>();
listOfSomething2.Add("first");
collection.Add(listOfSomething1);
collection.Add(listOfSomething2);
Because the second element is null after you clear the list.
Use:
String s = myList.get(0);
And remember, index 0 is the first element.
The right way to iterate on a list inside list is:
//iterate on the general list
for(int i = 0 ; i < collection.size() ; i++) {
ArrayList<String> currentList = collection.get(i);
//now iterate on the current list
for (int j = 0; j < currentList.size(); j++) {
String s = currentList.get(1);
}
}
A cleaner way of iterating the lists is:
// initialise the collection
collection = new ArrayList<ArrayList<String>>();
// iterate
for (ArrayList<String> innerList : collection) {
for (String string : innerList) {
// do stuff with string
}
}
I have String array like this
We have to pass data through response.body.getdata and this data pass in constructor like this,
List taginnerData;
"data": [
"banana",
"apple",
"grapes",
"Pears",
"Mango",
"Cherry",
"Guava",
"TorontoVsMilwaukee_12Jan19"
]
String[] myArray = new String[taginnerData.size()];
for (int i = 0; i < taginnerData.size(); i++) {
myArray[i] = String.valueOf(taginnerData.get(i));
holder.tv_channel_name.setText("" +taginnerData.get(i));
//we get any value from here to set in adapter
}

calculating the final length

The following code separates the duplicate names into 1 column and sum of numbers associated with the names into the second column.
Like :
Nokia 21
Blackberry 3
Nimbus 30
from the array given in the program.
I want to know the final length of the array that contain these entries. In this case 3. How do i calculate that ?
package keylogger;
import java.util.ArrayList;
import java.util.List;
public class ArrayTester {
private static int finalLength = 0;
private static String Name[][];
private static String data[][] = {
{"Nokia" , "7"},
{"Blackberry" ,"1"},
{"Nimbus","10"},
{"Nokia" , "7"},
{"Blackberry" , "1"},
{"Nimbus","10"},
{"Nokia" , "7"},
{"Blackberry" , "1"},
{"Nimbus","10"}
};
public void calculator() {
Name = new String[data.length][2];
List<String> marked = new ArrayList<String>();
try {
for(int i=0;i<data.length;i++) {
Name[i][0] = data[i][0];
Name[i][1] = data[i][1];
String name = data[i][0];
if(marked.contains(name)) {
continue;
}
marked.add(name);
int k = i + 1;
int v = k;
for (int j = 0; j < data.length - v; j++) {
String s = data[k][0];
if(Name[i][0].equalsIgnoreCase(s)) {
Name[i][0] = s;
Integer z = Integer.parseInt(Name[i][1]) + Integer.parseInt(data[k][1]);
Name[i][1] = z.toString();
}
k++;
}
}
}catch(Exception exc) {
exc.printStackTrace();
}
}
public static void main(String args[]) {
ArrayTester o = new ArrayTester();
o.calculator();
for(String s[] : Name) {
for(String x : s) {
System.out.println(x);
}
}
}
}
As usual, the "problem" is poor coding. Your entire program, properly written, can be reduced to just 3 lines of code (5 if you include defining the array and printing the output):
public static void main(String[] args) {
String data[][] = {{"Nokia", "7"}, {"Blackberry", "1"}, {"Nimbus", "10"},
{"Nokia", "7"}, {"Blackberry", "1"}, {"Nimbus", "10"}, {"Nokia", "7"},
{"Blackberry", "1"}, {"Nimbus", "10"}, {"Zebra", "78"}};
HashMap<String, Integer> totals = new HashMap<String, Integer>();
for (String[] datum : data)
totals.put(datum[0], new Integer(datum[1]) + (totals.containsKey(datum[0]) ? totals.get(datum[0]) : 0));
System.out.println("There are " + totals.size() + " brands: " + totals);
}
Output:
There are 4 brands: {Nimbus=30, Zebra=78, Nokia=21, Blackberry=3}
You can't know it a priori, the size will be known just when you'll have finished splitting the strings and doing your math.
In your example in the end marked.size() will have the size you are looking for but I'd suggest you to directly use a HashMap so that you won't care about searching for existing elements in linear time and then convert it to an array.
Something like:
String[][] names = new String[map.size()];
Set<String> keys = map.keys();
int c = 0;
for (String k : keys)
{
names[c] = new String[2];
names[c][0] = k;
names[c++][1] = map.get(k).toString();
}
As far as I understand it, you want to know the number of distinct names in your array without calling calculator(), right? I don't really know if that makes sense as you still have to go through every entry and compare it with a set. But you could do it with a Set:
private int getNumberOfEntries(String[][] data) {
Set<String> names = new HashSet<String>();
for (int i=0; i<data.length; i++) {
names.add(data[i][1]);
}
return names.size();
}
Now you can just call int n = getNumberOfEntries(data);...
EDIT: Of course it makes more sense to do the sums in the same step, see Bohemians solution for that.

Categories