Arraylist - Using switch statement to add string - java

I am new to programming and my professor has given an assignment that requires us to:
"declare on arraylist with the size of 5. Use switch statement to add string values to your arraylist. Retrieve the contents of your arraylist. Check the size of each element. If the element length is less than 8 rerun the program, otherwise count the consonants of each element."
I've done some research to understand some factors of an ArrayList;
to start off, I did this:
import java.util.ArrayList;
public class izeOfArrayList {
public static void main(String[] args) {
ArrayList arrayList = new ArrayList();
arrayList.add("1");
arrayList.add("2");
arrayList.add("3");
int totalElements = arrayList.size();
System.out.println("ArrayList contains...");
for(int index=0; index < totalElements; index++)
System.out.println(arrayList.get(index));
}
}
This code just gets the number of elements currently stored in my ArrayList, and prints out each element.
I have three questions:
How can I add String values using switch statement?
How can I retrieve the contents of my ArrayList?
How can I check the size of each element in my ArrayList?

"declare on arraylist with the size of 5. Use switch statement to add string values to your arraylist. Retrieve the contents of your arraylist. Check the size of each element. If the element length is less than 8 rerun the program, otherwise count the consonants of each element."
Let's decode line by line:
declare on arraylist with the size of 5.
ArrayList<String> myList = new ArrayList<>(5);
Our ArrayList needs to be defined as a list of Strings, so we put those in the angle brackets. The constructor takes a starting size, which is specified as 5.
Use switch statement to add string values to your arraylist.
Completely unintelligible. switch statements are used in flow of control; we can decide to add string values based on some condition, but we cannot generate input with switch statements, and no conditions are specified. This following code is (seemingly) valid for this instruction:
String values = "values";
switch (values) {
case "values":
default:
myList.add(values);
}
Retrieve the contents of your arraylist.
This you have already (mostly) written up:
int totalElements = myList.size();
for(int index = 0; index < totalElements; index++)
String tempElem = myList.get(index); //get access to the individual elem
//here we're going to do something with the current string (probably)
}
Check the size of each element.
I'm assuming that by the 'size of each element', your professor is looking for the length of each String.
int tempElemLength = tempElem.length();
String objects have a length method, it returns an int.
If the element length is less than 8 rerun the program, otherwise count the consonants of each element.
This, while at first glace seems reasonable, is again unintelligible. Here's a possible interpretation of this line:
if (tempElemLength < 8) {
main(null);
} else {
int tempElemNumConsonants = countConsonants(tempElem);
//consonants are counted and now what?
}
Here is a complete response to your assignment as it is currently defined:
import java.util.ArrayList;
public class SizeOfArrayList {
public static void main(String[] args) {
ArrayList<String> myList = new ArrayList<>(5);
String values = "values";
switch (values) {
case "values":
default:
myList.add(values);
}
int totalElements = myList.size();
for (int index = 0; index < totalElements; index++)
String tempElem = myList.get(index);
int tempElemLength = tempElem.length();
if (tempElemLength < 8) {
main(null);
} else {
int tempElemNumConsonants = countConsonants(tempElem);
//consonants are counted and now what?
//guess print them out?
System.out.println('Item ' + index + ': ' + tempElem + ' -> number of consonants: ' + tempElemNumConsonants);
}
}
}
}
This is a solution to your problem as it has been provided; I will bet money that this is not the solution to your homework problem.
In another school of thought, if the focus of the assignment is basic use and understanding of ArrayLists and I was your professor, the assignment that I would have intended to give my students would be as follows:
Declare and ArrayList with the size of 5. Prompt the user for values until they enter 'quit'; use a switch statement to add all String values into the ArrayList that aren't just a number from [0-9]. Loop over each element in the ArrayList; if the length of any String element is less than 8, alert the user then restart the program. If all of the lengths are valid, sum up the consonants of each element. Print out each word and the consonant count, along with a final tally of the number of words along with the total number of consonants.
While I do know that this does not help you with the initial question, I hope it might be able to help you understand what your professor is trying to ask of you.

Related

Throwing an IndexOutOfBoundsException and I don't understand how

the code in this class is throwing an "indexOutOfBounds exception". I don't understand why its throwing that, I'm just trying to loop through each row, and each column, then assign each column to a variable. For more clarification, initializeArray is a regular 2D ARRAY, and initializedArray is an ARRAYLIST.
//Array to initialize course list (format is first name, last name, student number}
//This is the array that I will be using to store each row into the ArrayList
String [] [] initializeArray =
{{"Hasan","Ahmed","462948"},
{"Abdul","Alvi","764226"},
{"Omar","Askalany","719049"},
{"Harsim","Grewal","438629"},
{"Anis","Habib","576510"},
{"Hamiz","Hasan","621802"},
{"Bilal","Hussain","417440"},
{"Mazhar","Jabakhan","603544"},
{"Tharsh","Kamalan","447615"},
{"Rohan","Kanjani","443604"}};
//Setting up an ordered collection class of Students using the values in initializeArray
//The parameter "Student", is a class. Student(String firstName, String lastName, String stuNum)
ArrayList<Student> initializedArray = new ArrayList<Student>();
//for every row in initializeArray
for(int row = 0; row<initializeArray.length; row++)
{
//for every column in initializeArray
for(int col = 0; col<initializeArray[row].length; col++)
{
String temp = initializeArray[row][col]; //set the first element to temp
String temp2 = initializeArray[row][col+1]; //set the second element to temp2
String temp3 = initializeArray[row][col+2]; //set the third element to temp3, this is where the run-time error is happening, but its happening with the other temp vars as well
initializedArray.add(new Student(temp, temp2, temp3));
}
}
System.out.println(initializedArray);
The problem is that your index is out of bounds just like the exception says.
Have a look at initializeArray[row][col+1]; and the loop condition col<initializeArray[row].length. What happens when col has the value initializeArray[row].length - 1 and you add 1? The index is outside the allowed range [0, initializeArray[row].length-1].
In your case you know that there are only 3 columns, so you probably just mean initializeArray[row][0], initializeArray[row][1] etc.
In other cases you actually might need to loop over an array and you might want to addess indices after the "current" one (e.g. array[i+1]) but in thos cases you need to make sure that the loop condition takes that into account or that you check inside the loop.
Assume you want to do some calculation based on the elements at i as well as i-1 and i+1 in one iteration. In that case your loop should be:
for(int i = 1;i < array.length - 1; i++)
That way you make sure that i-1 is never < 0 and i+1 is never >= array.length.
Update
As per the question in the comment, here's how you could iterate over the array to print (and for education purposes I'll use a foreach loop) - please note that this is an exception, don't add other questions here but post a new one to keep things simple:
for(Student student : initializedArray) {
System.out.println(student.getGivenName() + " " + student.getFamiliyName() + " " + student.getNumber());
}
Of course this assumes your Student class has those methods.
To make your life easier, override toString():
class Student {
... //other code
#Override
public String toString() {
return givenName + " " + familyName + " " + number;
}
}
Then when printing the list you should get something like "Hasan Ahmed 462948, Abdul Alvi 764226, ...". Using the foreach loop would then look like this:
for(Student student : initializedArray) {
System.out.println(student);
}
all you need to do is to remove the second loop and inside first your code will be like this :
String temp = initializeArray[row][0];
String temp2 = initializeArray[row][1];
String temp3 = initializeArray[row][2];
initializedArray.add(new Student(temp, temp2, temp3));
because when you loop inside initializeArray[row] and when you become to col equal to initializeArray[row].length the +1 and +2 will be out of bounds
I would do one loop with
if (initializeArray[row].length > 2) {
initializedArray.add(new Student(initializeArray[row][0], initializeArray[row][1], initializeArray[row][2]));
}
Otherwise, the condition for the inner loop should be
col < initializeArray[row].length - 2
given that you are accessing initializeArray[row][col + 2].

Adding elements dynamically in String array but index 0 showing null?

I want to add some values in string array dynamically by using for loop.
when i debug the code at first for loop it is showing values which are adding.I want to check if any one of the string equals to my given value.but in for loop 2 at index 0 it showing null and at index 1 it showing the string value.
for(int i=0;i<someval;i++) {
String[] mylist = new String[someval];
mylist[i]=previousVal;
System.out.println("Previous Value : " +mylist[i]);
}
for (int j = 0; j <=mylist.length; j++) {
if (mylist[j].equals(givenValue) ) { {
System.out.println("your value found in the array");
}
}
The problem is that you are creating a new array using
mylist = new String...
during each loop iteration.
So, it doesn't really matter if you write something to an array, if the next step consists of throwing that array away.
In other words: make sure that you create the array just once; preferable before entering your loop.

Read and print sequences and print merged sequence

I suppose to write a Java program using array and method follows: It reads a sequence of strings, each on a separate line, and stores them in an array, let call it input1, with one string per cell, in the order they were read. The sequence ends with an empty line: one with a String of length 0. Same thing with 2nd sequence.Then prints the 1st sequence and 2nd sequence. And then create an array that contains all of the elements of the above two arrays. Merging is done by alternating between the arrays: that is, the first cell of input1 is copied followed by the first cell of input2. Then the second cell of input1 is copied followed by the second cell of input2. Of course, in general, the two sequences may have different lengths, so after the shorter sequence is finished, all elements of the longer sequence are simply appended to the output array. Finally, prints the merged array with 1 string each line.
import java.util.Scanner;
public class A4 {
public static void readInput(Scanner myScanner, String[] input) {
boolean streamEnded = false;
int index = 0;
while (!streamEnded && myScanner.hasNext()) {
String value = myScanner.nextLine();
if (value.length() == 0) {
streamEnded = true;
input[index] = value;
} else {
input[index] = value;
index++;
}
}
}
public static void main(String[] args) {
int size = 5;
String[] input1 = new String[size];
String[] input2 = new String[size];
String[] store = new String[size*2];
Scanner aScanner = new Scanner(System.in);
readInput(aScanner, input1);
for (int i = 0; i < input1.length; i++) {
System.out.println("input[" + i +"]" + input1[i]);
}
readInput (aScanner, input2);
for (int i = 0; i < input2.length; i++) {
System.out.println("input[" + i +"]" + input2[i]);
}
}
}
i still dont know how to merge those 2 inputs together.Can anyone show me how to do it? Thanks
Declare three arrays for sequence 1, sequence 2 and merged-sequence.
Use a variable whichToUse to store which array to be used and assign array1 to it before the while loop, then store values into array1 on the place of System.out.print, then when first reach value.length()==0 ('=' is not designed for comparing, it's a mistake in your code.), you change the whichToUse point to array2. When the second reach value.length()==0, end the reading loop. One place to be marked, declare streamEnded as a int to count how many times we reach the value.length()==0. Only exit loop while streamEnded==2.
Now you have two arrays which contains the values from file. Next step is to merge them. Use a for loop to iterate items in merged-sequence, and use loop-counter%2 to determine which array to read when assign value to merged-sequence items. after any of the array1 and array2 reaches the end, read the other array in the rest of loop.
As looks like you are new to Java, I think write code by yourself is much better than I provide the code to you. If you've any other question, just comment here.

Is it possible to search through an array and return the index of the value

I am writing a simple Java program that basically stores an array of artists that have been in the charts previously; this is my code so far for the program
package searching;
import java.util.*;
public class Searching {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String artists[] = {"Rihanna", "Cheryl Cole", "Alexis Jordan", "Katy Perry", "Bruno Mars",
"Cee Lo Green", "Mike Posner", "Nelly", "Duck Sauce", "The Saturdays"};
System.out.println("Please enter an artist...");
String artist = scanner.nextLine();
}
}
I was just wondering, is it possible for the user to type the name of one of the artists, get the code to search the array and return the index of that value? and if so how would I go about it as I don't know where to begin... thanks in advance!
With an unsorted array, one option would be to put the artists in a List and use List.indexOf().
List<String> artistsList = Arrays.asList( artists );
...
int index = artistsList.indexOf( artist );
If the artists were sorted, you could use Arrays.binarySearch().
You need to loop through the artists array in a for loop and then return the index if the value equals the artist value.
for (int i = 0; i < artists.length; i++) {
String artistElement = artists[i];
if (artistElement.equals(artist)) {
System.out.println(i);
}
}
Here's what happened for me:
Please enter an artist...
Mike Posner
6
I was just wondering, is it possible for the user to type the name of one of the artists, get the code to search the array and return the index of that value?
Yes, it is possible.
Since you don't know where to begin, I would say you can start going through the array (probably using a for loop) and validating if the artist variable is equals to the current element of the array. If they're equals, then you can just return the current index of the element of the array. If nothing is found, then return a default value like -1 that you can handle and return a message like Artist not found.
You could do it like so:
int index = -1;
for (int i = 0; i < artists.length; i++) {
if (artist.equals(artists[i]))
index = i;
}
if (index == -1)
System.out.println("Artist not found");
else
System.out.println("Index of artist: " + index);
}
This isn't as eloquent as tieTYT's solution, but does the trick. The index is set to -1. The for loop compares each artist to each value in your array. If a match is found, the index is set to the index of the element.
After the for loop, if the index is still -1, the user is informed that no match was found, otherwise the appropriate artist and index are output.
The user of a for loop is the most common way to scroll through the contents of an array and compare elements against a given value. By calling artists[i], every element of the array can be checked against the input String.

How to get 2D array possible combinations

I have the following 2D array:
String[M][]
String[0]
"1","2","3"
String[1]
"A", "B"
.
.
.
String[M-1]
"!"
All the possible combinations should be in store in a resulting array
String[] combinations. So for example:
combinations[0] == {"1A....!")
combinations[1] == {"2A....!")
combinations[2] == {"3A....!")
combinations[3] == {"1B....!")
Notice that that the arrays are of variable length. Order of the elements in the output String doesn't matter. I also don't care if there are duplicates.
If the arrays were the same length, nested loops would do the trick, but they are not, and I really don't know how to approach the problem.
You can iterate through the combinations one at a time like clockwork by using an array to record the size of each inner array, and a counter array which keeps track of which member to use from each inner array. Something like this method:
/**
* Produce a List<String> which contains every combination which can be
* made by taking one String from each inner String array within the
* provided two-dimensional String array.
* #param twoDimStringArray a two-dimensional String array which contains
* String arrays of variable length.
* #return a List which contains every String which can be formed by taking
* one String from each String array within the specified two-dimensional
* array.
*/
public static List<String> combinations(String[][] twoDimStringArray) {
// keep track of the size of each inner String array
int sizeArray[] = new int[twoDimStringArray.length];
// keep track of the index of each inner String array which will be used
// to make the next combination
int counterArray[] = new int[twoDimStringArray.length];
// Discover the size of each inner array and populate sizeArray.
// Also calculate the total number of combinations possible using the
// inner String array sizes.
int totalCombinationCount = 1;
for(int i = 0; i < twoDimStringArray.length; ++i) {
sizeArray[i] = twoDimStringArray[i].length;
totalCombinationCount *= twoDimStringArray[i].length;
}
// Store the combinations in a List of String objects
List<String> combinationList = new ArrayList<String>(totalCombinationCount);
StringBuilder sb; // more efficient than String for concatenation
for (int countdown = totalCombinationCount; countdown > 0; --countdown) {
// Run through the inner arrays, grabbing the member from the index
// specified by the counterArray for each inner array, and build a
// combination string.
sb = new StringBuilder();
for(int i = 0; i < twoDimStringArray.length; ++i) {
sb.append(twoDimStringArray[i][counterArray[i]]);
}
combinationList.add(sb.toString()); // add new combination to list
// Now we need to increment the counterArray so that the next
// combination is taken on the next iteration of this loop.
for(int incIndex = twoDimStringArray.length - 1; incIndex >= 0; --incIndex) {
if(counterArray[incIndex] + 1 < sizeArray[incIndex]) {
++counterArray[incIndex];
// None of the indices of higher significance need to be
// incremented, so jump out of this for loop at this point.
break;
}
// The index at this position is at its max value, so zero it
// and continue this loop to increment the index which is more
// significant than this one.
counterArray[incIndex] = 0;
}
}
return combinationList;
}
How the method works
If you imagine the counter array being like a digital clock reading then the first String combination sees the counter array at all zeroes, so that the first String is made by taken the zero element (first member) of each inner array.
To get the next combination the counter array is incremented by one. So the least-significant counter index is increased by one. If this causes its value to become equal to the length of the inner array it represents then the index is zeroed, and the next index of greater significance is increased. A separate size array stores the length of each inner array, so that the counter array loop knows when an index has reached its maximum.
For example, if the size array was:
[3][3][2][1]
and the counter array was at:
[0][2][1][0]
then the increment would make the least significant (right-most) index equal to 1, which is its maximum value. So that index gets zeroed and the next index of greater significance (the second-from-right) gets increased to 2. But that is also the maximum of that index, so it gets zeroed and we move to the next index of greater significance. That gets increased to three, which is its maximum value so it gets zeroed and we move to the most significant (left-most) index. That gets increased to 1, which is less than its maximum so the incremented counter array becomes:
[1][0][0][0]
Which means the next String combination is made by taking the second member of the first inner array, and the first member of the next three inner arrays.
Dire warnings and notes
I wrote this just now in about forty minutes, and it's half-one in the morning, which means that even though it seems to do exactly what is needed, there are very likely bugs or bits of code which could be optimised. So be sure to unit test it thoroughly if its performance is critical.
Note that it returns a List rather than a String array because I think that Java Collections are vastly preferable to using arrays in most cases. Also, if you need a result set with no duplicates, you can simply change the List to a Set which will automatically drop duplicates and leave you with a unique set.
If you really need the result as a String array, don't forget you can use the List<String>.toArray(String[]) method to simply convert the returned List to what you need.
This problem has a very nice recursive structure to it (which also means it could explode in memory, the correct way should be using iterators such as the other answer, but this solution looks nicer imo and we can prove correctness inductively because of the recursive nature). A combination consists of an element from the first list attached to all possible combinations formed from the remaining (n-1) lists. The recursive work is done in AllCombinationsHelper, but you invoke AllCombinations. Note to test for empty lists and more extensively.
public static List<String> AllCombinations(List<List<Character>> aList) {
if(aList.size() == 0) { return new ArrayList<String>(); }
List<Character> myFirstSubList = aList.remove(0);
List<String> myStrings = new ArrayList<String>();
for(Character c : myFirstSubList) {
myStrings.add(c.toString());
}
return AllCombinationsHelper(aList, myStrings);
}
public static List<String> AllCombinationsHelper(List<List<Character>> aList,
List<String> aCollection) {
if(aList.size() == 0) { return aCollection; }
List<Character> myFirstList = aList.remove(0);
List<String> myReturnSet = new ArrayList<String>();
for(String s : aCollection) {
for(Character c : myFirstList) {
myReturnSet.add(c + s);
}
}
return AllCombinationsHelper(aList, myReturnSet);
}
Should be straight forward to do with recursion.
Let me rephrase a bit, so the terminology is less confusing.
We will call String[] as Token List, which is a list of Tokens
Now you have a List of Token List, you want to get one Token from each Token List available, and find out all combination.
What you need to do is, given a list of TokenList
If the List is having only one TokenList, the content of the Token List itself is all combinations
Else, make a sub-list by excluding the first Token List, and find out all combinations of that sub list. When you have the combinations, the answer is simply loop through your first token list, and generate all combinations using each token in the token list, and the result combinations.
I am only giving a psuedo code:
List<String> allCombinations(List<TokenList> listOfTokenList) {
if (length of strings == 1) {
return strings[0];
}
List<String> subListCombinations
= allCombination(listOfTokenList.subList(1)); // sublist from index 1 to the end
List<String> result;
for each (token in listOfTokenList[0]) {
for each (s in subListCombination) {
result.add(token + s);
}
}
return result;
}
I have been struggling with this problem for some time. But I finally solved it. My main obstacle was the SCOPE I used for declaring each variable. If you do not declare your variables in the correct scope, then the variable will retain changes made in the previous iteration.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class RecursiveAlgorithmTest {
private static int recursiveCallsCounter = 0;
public static ArrayList<ArrayList<String>> testCases = new ArrayList<ArrayList<String>>();
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
//set values for ArrayOfArrays
ArrayList<String> VariableA = new ArrayList<String>(Arrays.asList("red", "green"));
ArrayList<String> VariableB = new ArrayList<String>(Arrays.asList("A", "B", "C"));
ArrayList<String> VariableC = new ArrayList<String>(Arrays.asList("1", "2", "3", "4"));
ArrayList<ArrayList<String>> AofA = new ArrayList<ArrayList<String>>();
AofA.add(VariableA); AofA.add(VariableB); AofA.add(VariableC);
System.out.println("Array of Arrays: ToString(): " +AofA.toString());
ArrayList<String> optionsList = new ArrayList<String>();
//recursive call
recurse(optionsList, AofA, 0);
for (int i = 0 ; i < testCases.size() ; i++) {
System.out.println("Test Case " + (i+1) + ": " + testCases.get(i));
}
}//end main(String args[])
private static void recurse(ArrayList<String> newOptionsList,
ArrayList<ArrayList<String>> newAofA, int placeHolder){
recursiveCallsCounter++;
System.out.println("\n\tStart of Recursive Call: " + recursiveCallsCounter);
System.out.println("\tOptionsList: " + newOptionsList.toString());
System.out.println("\tAofA: " + newAofA.toString());
System.out.println("\tPlaceHolder: "+ placeHolder);
//check to see if we are at the end of all TestAspects
if(placeHolder < newAofA.size()){
//remove the first item in the ArrayOfArrays
ArrayList<String> currentAspectsOptions = newAofA.get(placeHolder);
//iterate through the popped off options
for (int i=0 ; i<currentAspectsOptions.size();i++){
ArrayList<String> newOptions = new ArrayList<String>();
//add all the passed in options to the new object to pass on
for (int j=0 ; j < newOptionsList.size();j++) {
newOptions.add(newOptionsList.get(j));
}
newOptions.add(currentAspectsOptions.get(i));
int newPlaceHolder = placeHolder + 1;
recurse(newOptions,newAofA, newPlaceHolder);
}
} else { // no more arrays to pop off
ArrayList<String> newTestCase = new ArrayList<String>();
for (int i=0; i < newOptionsList.size();i++){
newTestCase.add(newOptionsList.get(i));
}
System.out.println("\t### Adding: "+newTestCase.toString());
testCases.add(newTestCase);
}
}//end recursive helper
}// end of test class
In Python one uses itertools.product and argument unpacking (apply)
>>> import itertools
>>> S=[['1','2','3'],['A','B'],['!']]
>>> ["".join(x) for x in itertools.product(*S)]
['1A!', '1B!', '2A!', '2B!', '3A!', '3B!']

Categories