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
Related
I have a class called ThreeSorts.java
The aim is to generate a random arraylist of size n - this works.
Then display the array - this works.
Then I have to prove that these sorting algorithms work, however when I pass the random generated array into one of the sorts like SortA(a);
and then display the array it does not get sorted the output is the same:
Generated ArrayList : (153),(209),(167),(117),(243),(67),(0),(148),(39),(188),
SortA ArrayList : (153),(209),(167),(117),(243),(67),(0),(148),(39),(188),
ThreeSorts.java:
import java.util.*;
public class ThreeSorts
{
private static ArrayList<Integer> CopyArray(ArrayList<Integer> a)
{
ArrayList<Integer> resa = new ArrayList<Integer>(a.size());
for(int i=0;i<a.size();++i) resa.add(a.get(i));
return(resa);
}
public static ArrayList<Integer> SortA(ArrayList<Integer> a)
{
ArrayList<Integer> array = CopyArray(a);
int n = a.size(),i;
boolean noswaps = false;
while (noswaps == false)
{
noswaps = true;
for(i=0;i<n-1;++i)
{
if (array.get(i) < array.get(i+1))
{
Integer temp = array.get(i);
array.set(i,array.get(i+1));
array.set(i+1,temp);
noswaps = false;
}
}
}
return(array);
}
public static ArrayList<Integer> SortB(ArrayList<Integer> a)
{
ArrayList<Integer> array = CopyArray(a);
Integer[] zero = new Integer[a.size()];
Integer[] one = new Integer[a.size()];
int i,b;
Integer x,p;
//Change from 8 to 32 for whole integers - will run 4 times slower
for(b=0;b<8;++b)
{
int zc = 0;
int oc = 0;
for(i=0;i<array.size();++i)
{
x = array.get(i);
p = 1 << b;
if ((x & p) == 0)
{
zero[zc++] = array.get(i);
}
else
{
one[oc++] = array.get(i);
}
}
for(i=0;i<oc;++i) array.set(i,one[i]);
for(i=0;i<zc;++i) array.set(i+oc,zero[i]);
}
return(array);
}
public static ArrayList<Integer> SortC(ArrayList<Integer> a)
{
ArrayList<Integer> array = CopyArray(a);
SortC(array,0,array.size()-1);
return(array);
}
public static void SortC(ArrayList<Integer> array,int first,int last)
{
if (first < last)
{
int pivot = PivotList(array,first,last);
SortC(array,first,pivot-1);
SortC(array,pivot+1,last);
}
}
private static void Swap(ArrayList<Integer> array,int a,int b)
{
Integer temp = array.get(a);
array.set(a,array.get(b));
array.set(b,temp);
}
private static int PivotList(ArrayList<Integer> array,int first,int last)
{
Integer PivotValue = array.get(first);
int PivotPoint = first;
for(int index=first+1;index<=last;++index)
{
if (array.get(index) > PivotValue)
{
PivotPoint = PivotPoint+1;
Swap(array,PivotPoint,index);
}
}
Swap(array,first,PivotPoint);
return(PivotPoint);
}
/////////////My Code////////////////
public static ArrayList<Integer> randomArrayList(int n)
{
ArrayList<Integer> list = new ArrayList<>();
Random random = new Random();
for (int i = 0; i < n; i++)
{
list.add(random.nextInt(255));
}
return list;
}
private static void showArray(ArrayList<Integer> a) {
for (Iterator<Integer> iter = a.iterator(); iter.hasNext();)
{
Integer x = (Integer)iter.next();
System.out.print(("("+x + ")"));
System.out.print(",");
//System.out.print(GetAge());
//System.out.print(") ");
}
System.out.println();
}
static void test(int n) {
//int n = 13;
ArrayList<Integer> a = randomArrayList(n);
System.out.println("Generated ArrayList : ");
showArray(a);
System.out.println("SortA ArrayList : ");
SortA(a);
showArray(a);
}
}
Test is called in main like this ThreeSorts.test(10);
Why is it not getting sorted even tho the random array is passed and there are no errors?
In your sample code you are only testing SortA which reads:
ArrayList<Integer> array = CopyArray(a);
...
return(array);
so actually it is taking a copy of your array, sorting it, and then returning you the sorted array.
So when you test it, instead of using:
SortA(a);
you need to use
a = SortA(a);
The type of data your function SortA returns is ArrayList<Integer>, which means it returns an array list of integers. You need to change the line SortA(a); to a = SortA(a);: this way a variable will receive the results of this function's work.
You have to set the returned value, otherwise a will not be sorted in test method. Change the way you call SortA(a) to:
static void test(int n) {
//int n = 13;
ArrayList<Integer> a = randomArrayList(n);
System.out.println("Generated ArrayList : ");
showArray(a);
System.out.println("SortA ArrayList : ");
a = SortA(a);
showArray(a);
}
instead of the method SortA(a); just use Collections.sort(a); inside static block. Like
ArrayList<Integer> a = randomArrayList(n);
System.out.println("Generated ArrayList : ");
showArray(a);
System.out.println("SortA ArrayList : ");
Collections.sort(a);
showArray(a);
Thats it.
How to retrieve element from ArrayList<long[]>?
I wrote like this:
ArrayList<long []> dp=new ArrayList<>();
//m is no of rows in Arraylist
for(int i=0;i<m;i++){
dp.add(new long[n]); //n is length of each long array
//so I created array of m row n column
}
Now how to get each element?
every element in that list is an array... so you need to carefully add those by:
using anonymous arrays new long[] { 1L, 2L, 3L }
or especifying the size using the new keyword new long[5]
public static void main(String[] args) throws Exception {
ArrayList<long[]> dp = new ArrayList<>();
// add 3 arrays
for (int i = 0; i < 3; i++) {
dp.add(new long[] { 1L, 2L, 3L });
}
// add a new array of size 5
dp.add(new long[5]); //all are by defaul 0
// get the info from array
for (long[] ls : dp) {
for (long l : ls) {
System.out.println("long:" + l);
}
System.out.println("next element in the list");
}
}
You get the arrays the same way you get anything from an ArrayList. For example, to get the tenth long[] stored in the ArrayList, you'd use the get method:
long[] tenthArray = dp.get(9);
You could also have an ArrayList of objetcs that contain an array of longs inside. But the problem so far with your code is that you are not putting any values in each long array.
public class NewClass {
private static class MyObject {
private long []v;
public MyObject(int n) {
v = new long[n];
}
#Override
public String toString() {
String x = "";
for (int i = 0; i < v.length; i++) {
x += v[i] + " ";
}
return x;
}
}
public static void main(String[] args) {
ArrayList<MyObject> dp = new ArrayList();
int m = 3;
int n = 5;
for (int i = 0; i < m; i++) {
dp.add(new MyObject(n));
}
for (MyObject ls : dp) {
System.out.println(ls);
}
}
}
I got a problem when insert an ArrayList into ArrayList.
My source code:
import java.util.ArrayList;
public class Ask {
public static void main(String[] args) {
ArrayList<String> mentah = new ArrayList<String>();
mentah.add("Reza");
mentah.add("Fata");
mentah.add("Faldy");
mentah.add("Helsan");
mentah.add("Dimas");
mentah.add("Mamun");
mentah.add("Erik");
mentah.add("Babeh");
mentah.add("Tio");
mentah.add("Mamang");
ArrayList<ArrayList<String>> result =new ArrayList<ArrayList<String>>();
result.add(mentah);
}
}
How can I create a list based on that data; that will look like:
[[data1,data2,data3],[data4,data5,data6],[data7,data8,data9,data10]]
10 div 3 is 3 (so 3 elements per sublist)
10 mod 3 is 1 (so last sublist has 4 entries)
10 divide by 3 is
3 3 4
Just upgraded the answer of #Narayana Ganesh:
ArrayList<String> mentah = new ArrayList<String>();
mentah.add("Reza");
mentah.add("Fata");
mentah.add("Faldy");
mentah.add("Helsan");
mentah.add("Dimas");
mentah.add("Mamun");
mentah.add("Erik");
mentah.add("Babeh");
mentah.add("Tio");
mentah.add("Mamang");
List<List<String>> result = new ArrayList<List<String>>();
for (int j= 0; j< mentah.size() ; j+=3) {
int end = mentah.size() <= j+2 ? mentah.size() : j+3;
if(mentah.size() - j == 4) end = end +1;
if(j != 9) result.add(mentah.subList(j, end));
}
System.out.println(result);
}
Result:
[[Reza, Fata, Faldy], [Helsan, Dimas, Mamun], [Erik, Babeh, Tio, Mamang]]
A more generic solution would look like:
List<String> allNames = Arrays.asList("Reza", "Fata", ...
List<List<String>> slicedNames = new ArrayList<>();
List<String> sublist = new ArrayList<>();
int sublistTargetLength = 3;
for (String name : allNames) {
sublist.add(name);
if (sublist.size() == sublistTargetLength) {
slicedNames.add(sublist);
sublist = new ArrayList<>();
}
}
if (sublist.size() > 0) {
slicedNames.get(slicedNames.size()-1).addAll(sublist);
}
Some notes:
The above iterates your initial list of names (which can created using that single call to Arrays.asList()); and puts the entries into same-sized lists; which are then added to the slicedNames list of list.
If there is any "remaining" data; that is simply added to the last element of the list of list.
You should prefer to use the interface type List for your variable types; you only use the specific implementation class (ArrayList) when instantiating the list
When iterating anything, prefer the for-each looping style when possible
Try this. You can achieve this using subList method.
import java.util.ArrayList;
import java.util.List;
public class Ask {
public static void main(String[] args) {
ArrayList<String> mentah = new ArrayList<String>();
mentah.add("Reza");
mentah.add("Fata");
mentah.add("Faldy");
mentah.add("Helsan");
mentah.add("Dimas");
mentah.add("Mamun");
mentah.add("Erik");
mentah.add("Babeh");
mentah.add("Tio");
mentah.add("Mamang");
List<List<String>> result = new ArrayList<List<String>>();
for (int j= 0; j< mentah.size() ; j+=3) {
int end = mentah.size() <= j+2 ? mentah.size() : j+3;
result.add(mentah.subList(j, end));
}
for (List<String> item : result) {
System.out.println(" - -"+item);
}
}
}
First create sublists with a maximal size of 3 which will give you something like this
[[Reza, Fata, Faldy], [Helsan, Dimas, Mamun], [Erik, Babeh, Tio], [Mamang]]
then check if the last sublist size is less than 3 if yes add this to the second last sublist and remove the last one
public class Example {
public static void main(String[] args) {
List<String> mentah = new ArrayList<>();
mentah.add("Reza");
mentah.add("Fata");
mentah.add("Faldy");
mentah.add("Helsan");
mentah.add("Dimas");
mentah.add("Mamun");
mentah.add("Erik");
mentah.add("Babeh");
mentah.add("Tio");
mentah.add("Mamang");
List<List<String>> parts = new ArrayList<>();
int sizeOfOriginalList = mentah.size();
int sizeOfSubLists = 3;
for (int i = 0; i < sizeOfOriginalList; i += sizeOfSubLists) {
parts.add(new ArrayList<>(mentah.subList(i, Math.min(sizeOfOriginalList, i + sizeOfSubLists))));
}
if(parts.get(parts.size()-1).size()<sizeOfSubLists){
parts.get(parts.size()-2).addAll(parts.get(parts.size()-1));
parts.remove(parts.get(parts.size()-1));
}
System.out.println(parts);
}
}
I need to create a JAVA method: public static int[] Numb() that reads and returns a series of positive integer values. If the user enters -1 we should stop accepting values, and then I want to call it in the main method. And we should return to the user integers that he entered them, with the total number.
So if he entered the following:
5 6 1 2 3 -1
So the total number is : 6
The numbers entered are: 5 6 1 2 3 -1
I tried the following:
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
}
public static int[] readNumbers(int[] n)
{
int[] a = new int[n.length];
Scanner scan = new Scanner(System.in);
for(int i = 0;i<n.length;i++) {
String token = scan.next();
a[i] = Integer.nextString();
}
}
}
And here is a fiddle of them. I have an error that said:
Main.java:21: error: cannot find symbol
a[i] = Integer.nextString();
I am solving this exercise step by step, and I am creating the method that reads integers. Any help is appreciated.
Integer.nextString() doesn't exist, to get the next entered integer value, you may change your loop to either :
for(int i = 0;i<n.length;i++) {
a[i] = scan.nextInt();
}
or as #vikingsteve suggested :
for(int i = 0;i<n.length;i++) {
String token = scan.next();
a[i] = Integer.parseInt(token);
}
public static void main(String[] args) {
List<Integer> numList = new ArrayList<>();
initializeList(numList);
System.out.println("Num of integer in list: "+numList.size());
}
public static void initializeList(List<Integer> numList) {
Scanner sc = new Scanner(System.in);
boolean flag = true;
while(flag) {
int num = sc.nextInt();
if(num==-1) {
flag = false;
}else {
numList.add(num);
}
}
sc.close();
}
Since the number of integers is unknown, use ArrayList. It's size can be altered unlike arrays.
You can create something like arraylist on your own..it can be done like this:
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
CustomArray c = new CustomArray(3);
boolean flag = true;
while (flag) {
int num = sc.nextInt();
if (num == -1) {
flag = false;
} else {
c.insert(num);
}
System.out.println(Arrays.toString(c.numList));
}
sc.close();
}
}
class CustomArray {
int[] numList;
int size; // size of numList[]
int numOfElements; // integers present in numList[]
public CustomArray(int size) {
// TODO Auto-generated constructor stub
numList = new int[size];
this.size = size;
numOfElements = 0;
}
void insert(int num) {
if (numOfElements < size) {
numList[numOfElements++] = num;
} else {
// list is full
size = size * 2; //double the size, you can use some other factor as well
//create a new list with new size
int[] newList = new int[size];
for (int i = 0; i < numOfElements; i++) {
//copy all the elements in new list
newList[i] = numList[i];
}
numList = newList;//make numList equal to new list
numList[numOfElements++] = num;
}
}
}
I have a double ArrayList in java like this.
List<double[]> values = new ArrayList<double[]>(2);
Now what I want to do is to add 5 values in zero index of list and 5 values in index one through looping.
The zeroth index would have values {100,100,100,100,100}
The index 1 would have values {50,35,25,45,65}
and all of these values are stored in a double array in following order
double[] values = {100,50,100,35,100,25,100,45,100,65}
How can i do it?
#Ahamed has a point, but if you're insisting on using lists so you can have three arraylist like this:
ArrayList<Integer> first = new ArrayList<Integer>(Arrays.AsList(100,100,100,100,100));
ArrayList<Integer> second = new ArrayList<Integer>(Arrays.AsList(50,35,25,45,65));
ArrayList<Integer> third = new ArrayList<Integer>();
for(int i = 0; i < first.size(); i++) {
third.add(first.get(i));
third.add(second.get(i));
}
Edit:
If you have those values on your list that below:
List<double[]> values = new ArrayList<double[]>(2);
what you want to do is combine them, right? You can try something like this:
(I assume that both array are same sized, otherwise you need to use two for statement)
ArrayList<Double> yourArray = new ArrayList<Double>();
for(int i = 0; i < values.get(0).length; i++) {
yourArray.add(values.get(0)[i]);
yourArray.add(values.get(1)[i]);
}
How about
First adding your desired result as arraylist and
and convert to double array as you want.
Try like this..
import java.util.ArrayList;
import java.util.List;
public class ArrayTest {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
// Your Prepared data.
List<double[]> values = new ArrayList<double[]>(2);
double[] element1 = new double[] { 100, 100, 100, 100, 100 };
double[] element2 = new double[] { 50, 35, 25, 45, 65 };
values.add(element1);
values.add(element2);
// Add the result to arraylist.
List<Double> temp = new ArrayList<Double>();
for(int j=0;j<values.size(); j++) {
for (int i = 0; i < values.get(0).length; i++) {
temp.add(values.get(0)[i]);
temp.add(values.get(1)[i]);
}
}
// Convert arraylist to int[].
Double[] result = temp.toArray(new Double[temp.size()]);
double[] finalResult = new double[result.length]; // This hold final result.
for (int i = 0; i < result.length; i++) {
finalResult[i] = result[i].doubleValue();
}
for (int i = 0; i < finalResult.length; i++) {
System.out.println(finalResult[i]);
}
}
}
ArrayList<ArrayList> arrObjList = new ArrayList<ArrayList>();
ArrayList<Double> arrObjInner1= new ArrayList<Double>();
arrObjInner1.add(100);
arrObjInner1.add(100);
arrObjInner1.add(100);
arrObjInner1.add(100);
arrObjList.add(arrObjInner1);
You can have as many ArrayList inside the arrObjList. I hope this will help you.
create simple method to do that for you:
public void addMulti(String[] strings,List list){
for (int i = 0; i < strings.length; i++) {
list.add(strings[i]);
}
}
Then you can create
String[] wrong ={"1","2","3","4","5","6"};
and add it with this method to your list.
Use two dimensional array instead. For instance, int values[][] = new int[2][5]; Arrays are faster, when you are not manipulating much.
import java.util.*;
public class HelloWorld{
public static void main(String []args){
List<String> threadSafeList = new ArrayList<String>();
threadSafeList.add("A");
threadSafeList.add("D");
threadSafeList.add("F");
Set<String> threadSafeList1 = new TreeSet<String>();
threadSafeList1.add("B");
threadSafeList1.add("C");
threadSafeList1.add("E");
threadSafeList1.addAll(threadSafeList);
List mainList = new ArrayList();
mainList.addAll(Arrays.asList(threadSafeList1));
Iterator<String> mainList1 = mainList.iterator();
while(mainList1.hasNext()){
System.out.printf("total : %s %n", mainList1.next());
}
}
}
You can pass an object which is refering to all the values at a particular index.
import java.util.ArrayList;
public class HelloWorld{
public static void main(String []args){
ArrayList<connect> a=new ArrayList<connect>();
a.add(new connect(100,100,100,100,100));
System.out.println(a.get(0).p1);
System.out.println(a.get(0).p2);
System.out.println(a.get(0).p3);
}
}
class connect
{
int p1,p2,p3,p4,p5;
connect(int a,int b,int c,int d,int e)
{
this.p1=a;
this.p2=b;
this.p3=c;
this.p4=d;
this.p5=e;
}
}
Later to get a particular value at a specific index, you can do this:
a.get(0).p1;
a.get(0).p2;
a.get(0).p3;.............
and so on.