Passing a string array as a parameter to a function java - java

I would like to pass a string array as a parameter to a function. Please look at the code below
String[] stringArray = {'a', 'b', 'c', 'd', 'e'};
functionFoo(stringArray);
Instead of:
functionFoo('a', 'b', 'c', 'd', 'e');
but if I do this I am getting an error stating that convert String[] into String. I would like to know if it is possible to pass the values like that or what is the correct way to do it.

How about:
public class test {
public static void someFunction(String[] strArray) {
// do something
}
public static void main(String[] args) {
String[] strArray = new String[]{"Foo","Bar","Baz"};
someFunction(strArray);
}
}

All the answers above are correct. But just note that you'll be passing the reference to the string array when you pass like this. If you make any modifications to the array in your called function, it will be reflected in the calling function also.
There is another concept called variable arguments in Java which you can look into. It basically works like this. Eg:-
String concat (String ... strings)
{
StringBuilder sb = new StringBuilder ();
for (int i = 0; i < strings.length; i++)
sb.append (strings [i]);
return sb.toString ();
}
Here we can call the function like concat(a,b,c,d) or any number of params you want.
More Info: http://today.java.net/pub/a/today/2004/04/19/varargs.html

I believe this should be the way this is done...
public static void function(String [] array){
...
}
And the calling will be done like...
public void test(){
String[] stringArray = {"a","b","c","d","e","f","g","h","t","k","k","k","l","k"};
function(stringArray);
}

look at familiar main method which takes string array as param

More than likely your method declaration is incorrect. Make sure the methods parameter is of type String array (String[]) and not simply String and that you use double quotes around your strings in the array declaration.
private String[] stringArray = {"a","b","c","d","e","f","g","h","t","k","k","k"};
public void myMethod(String[] myArray) {}

Feel free to use this how ever you like.
/*
* The extendStrArray() method will takes a number "n" and
* a String Array "strArray" and will return a new array
* containing 'n' new positions. This new returned array
* can then be assigned to a new array, or the existing
* one to "extend" it, it contain the old value in the
* new array with the addition n empty positions.
*/
private String[] extendStrArray(int n, String[] strArray){
String[] old_str_array = strArray;
String[] new_str_array = new String[(old_str_array.length + n)];
for(int i = 0; i < old_str_array.length; i++ ){
new_str_array[i] = old_str_array[i];
}//end for loop
return new_str_array;
}//end extendStrArray()
Basically I would use it like this:
String[] students = {"Tom", "Jeff", "Ashley", "Mary"};
// 4 new students enter the class so we need to extend the string array
students = extendStrArray(4, students); //this will effectively add 4 new empty positions to the "students" array.

I think you forget to register the parameter as String[]

please check the below code for more details
package FirstTestNgPackage;
import java.util.ArrayList;
import java.util.Arrays;
public class testingclass {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
System.out.println("Hello");
int size = 7;
String myArray[] = new String[size];
System.out.println("Enter elements of the array (Strings) :: ");
for(int i=0; i<size; i++)
{
myArray[i] = "testing"+i;
}
System.out.println(Arrays.toString(myArray));
ArrayList<String> myList = new ArrayList<String>(Arrays.asList(myArray));
System.out.println("Enter the element that is to be added:");
myArray = myList.toArray(myArray);
someFunction(myArray);
}
public static void someFunction(String[] strArray)
{
System.out.println("in function");
System.out.println("in function length"+strArray.length );
System.out.println(Arrays.toString(strArray));
}
}
just copy it and past... your code.. it will work.. and then you understand how to pass string array as a parameter ...
Thank you

Related

Display ArrayList of char in Java

I am working on the first part of a String permutation problem and I am just looping over the first char of a string and swap it with every following char of that same String. I initialized an empty ArrayList to store all of those permutations called listeFinale. When I am printing that ArrayList, I am getting a collection of object and not values ([[C#61bbe9ba, [C#61bbe9ba, [C#61bbe9ba, [C#61bbe9ba]), how can I print each char stored in the ArrayList?
import java.util.ArrayList;
import java.util.List;
public class checkPermu {
public static void main(String[] args) {
String myString = "aabc";
applyPermu(myString);
}
public static void applyPermu(String toCheck){
char[] newString = toCheck.toCharArray();
List listeFinale = new ArrayList();
for(int i = 0 ; i < newString.length ; i ++){
char temp = newString[0];
newString[0] = newString[i];
newString[i] = temp;
listeFinale.add(newString);
System.out.println(listeFinale);
}
}
}
First of all, don't use raw types for your List please.. Change:
List listeFinale = new ArrayList();
to:
List<char[]> listeFinale = new ArrayList<>();
As for your actual problem. Those values you see are the default toString() outputs of your inner character-arrays. You could iterate over your list, and call the java.util.Arrays.toString(char[]) method for them like this:
listeFinale.forEach(arr -> System.out.println(Arrays.toString(arr)));
Or, if you want to print them back as String again, use new String(char[]):
listeFinale.forEach(arr -> System.out.println(new String(arr)));
Try it online.

Bubble Sorting string in an array

I'm trying to bubble sort string data that was input into an array in descending and ascending order.
The following is the code so far:
import java.util.*;
public class nextLineArray
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String names[]=new String[12];
System.out.println("Enter the 12 names: ");
//Load Array
for(int i = 0; i < 12; i++)
{
names[i] = input.nextLine();
}
//Print initial list
System.out.println("List of names via input:"+ names);
//Print descending order list
String descSort;
descSort=bubbleSortDesc(names);
System.out.println("Names listed sorted in descending order (via BubbleSort): "+descSort);
}
public static String bubbleSortDesc(String[] names)
{
String temp;
int passNum, i, result;
for(passNum=1; passNum <= 11; passNum++)
{
for(i = 0; i<=(11-passNum); i++)
{
result=names[i].compareToIgnoreCase(names[i+1]);
if(result>0)
{
temp=names[i];
names[i]=names[i+1];
names[i+1]=temp;
}
}
}
return names;
}
}
When I try to return the sorted array to the main method it gives me the following error on the return line:
Incompatible Types
Our online instructor just started us out with using multiple methods and arrays at the same time and it is quite confusing...please excuse me if any of my mistakes appear to be obvious.
Edit: I have fixed the initial problem thanks to Alexandre Santos in the comments, I am now running into a problem when executing the program after inputting the data, instead of printing the strings in the array it prints out
[Ljava.lang.String;#6d782f7c
Take a look at the method
public static String bubbleSortDesc(String[] names)
The return of that method is supposed to be a String (only one), but you are returning the parameter "names", which is an array of strings. The "[]" after the String identifies it as an array.
I am not going to do your homework for you, so a hint: check if the return type of the method bubbleSortDesc should be one String or an array of Strings.
Good luck.
There are 2 points to fix. First you should return String array
public static String[] bubbleSortDesc(String[] names)
and therefore you should define it like this:
String descSort[];
public static String bubbleSortDesc(String[] names)
should be
public static String[] bubbleSortDesc(String[] names)
and also declare descSort as String array.
Also you are just printing the array objects. This will not print the list for you. You have iterate over the array.
Include this in you code:
for (String name:names)
{
System.out.println(name);
}
Do the same for descSort too....
You can fix your print command by changing it to the following:
System.out.println("Names listed sorted in descending order (via BubbleSort): "+ java.util.Arrays.deepToString(descSort));
If you want the nitty gritty, descSort is a String[]. In Java when you convert String[] into a String it gives you that crazy string representation. You have to instead converte each entry in the array to a String individually. Fortunately the deepToString method will do that for you.

Using a returned ArrayList

I'm currently desperatly trying to get an ArrayList that I return from a function into a new ArrayList in my main function...
Here are the code snippets:
public static ArrayList<String> permute(String begin, String end) {
ArrayList<String> al=new ArrayList<String>();
//filling bla
return al;
}
and here's where I call the function in the main function:
ArrayList<String> arr =permute("","abc");
arr unfortunately is empty, and I have no idea how to get it to work :(
Thanks in advance
EDIT:
Here's the full code:
import java.util.*;
class Problem24 {
public static ArrayList<String> permute(String begin, String end) {
ArrayList<String> al=new ArrayList<String>();
if (end.length() <= 1) {
String s=begin+end;
al.add(s);
} else {
for (int i = 0; i < end.length(); i++) {
try {
String newString = end.substring(0, i) + end.substring(i + 1);
permute(begin + end.charAt(i), newString);
} catch (StringIndexOutOfBoundsException exception) {
exception.printStackTrace();
}
}
}
return al;
}
public static void main (String[] args)
{
ArrayList<String> arr =permute("","abc");
System.out.println(arr.get(0));
}
}
Your ArrayList is empty but not null which means that the returning part worked. In oder to use the values from the method you need to fill the ArrayList inside the method.
ps: You should use List list = new ArrayList() or
List list = permute("", "abc") which is a simple version of dependency injection and a better design of your program.
You're not adding the items from the recursive calls.
Try adding the al.addAll to your permute call:
al.addAll(permute(begin + end.charAt(i), newString));
before returning the value make sure you are filling the al List
al.add(begin);
al.add(end);
al.add("any other string");
return al;
Obviously something in wrong with the // filling bla part.
I'd start with replacing your code in // filling bla with al.add("TEST"); and see if you even get something out.
Also your method is static and the source array isn't passed in, which suggest that either your code is supposed to permute those strings somehow. Are you possibly acting upon a static array (i.e. permute all elements between begin and end), and the source array is empty?
import java.util.*;
class Problem24
{
public static ArrayList<String> permute(String begin, String end)
{
ArrayList<String> al=new ArrayList<String>();
if (endingString.length() <= 1)
{
String s=begin+end;
al.add(s);
}
else
{
for (int i = 0; i < end.length(); i++)
{
try
{
String newString = end.substring(0, i) + end.substring(i + 1);
al.add(permute(begin + end.charAt(i), newString));
}
catch (StringIndexOutOfBoundsException exception)
{
exception.printStackTrace();
}
}
}
return al;
}
public static void main (String[] args)
{
ArrayList<String> arr = permute("","abc");
System.out.println(arr.get(0));
}
}
hope i corrected it the right way.
You call your method permute recurrently --- but you make no use of what it returns when it returns. In other words, you create a new array each time you call permute, but everything you get in for-loop is lost, as you are not passing it to next permute() calls --- eventually you return an empty array in which you didn't put anything.

'transferring' StringBuilder contents to a new ArrayList in java

If I have two class constants:
List<String> workingList= new ArrayList<String>();
StringBuilder holder = new StringBuilder(50);
both residing within, call it class StringParser and primary method readStuff()...
public class StringParser{
public void readStuff(){
//parsing logic and adding <String> elements to
//said workingList...
}//end of method readStuff
followed by a method where I inspect the contents of workingList...
public String someReaderMethod()
{
int ind = 0;
for(int i = 0; i < workingList.size();i++)
{
if(workingList.get(i).contains(someExp))
{
workingList.remove(ind);
holder.append(workingList.get(i).toString());
}
else
{
++ind;
}
}
return holder.toString();
}
...given that StringBuilder holder now contains what workingList has removed, is there a way I can 'pass' the contents of StringBuilder to a new ArrayList?
Is there a reason why you want to use a StringBuilder? You can directly insert the values into a new ArrayList. I think you could do it in a simpler way.
List<String> discardedList = new ArrayList<String>();
public void readStuff() {}
public static List<String> someReaderMethod()
{
for(int i = 0; i < workingList.size(); i++)
{
if(workingList.get(i).contains(someExp))
{
discardedList.add(workingList.get(i));
workingList.remove(i);
}
}
return discardedList;
}
You will need a deliminator to parse string and then you can use Split method and convert String[] to ArrayList.
holder.append(tempList.get(i));
holder.append(";");//Deliminator
Now when you have to use it you need to do
String[] strings =holderString.split(";");
List<String> list = Arrays.asList(strings);
While appending your List elements to your StringBuilder object, you need to append an extra delimiter after every append..
Later on, you can split the String in StringBuilder on that delimiter, and then convert your String array thus obtained to an ArrayList..

Java, getter for array values (array dynamically defined)

I have a series of String[] arrays which are list of words. Something like:
String[] ListOne = new String[100];
String[] ListTwo = new String[100];
/*And so on with other lists */
ListOne[0] = "word00";
ListOne[1] = "word01";
/*And so on till*/
ListLast[99] = "word 99 from last list";
Now I want a function for each list that, given a number returns the corresponding element (word):
public String GetFromListOne(int key) { return ListOne[key];}
Is there a way to avoid manually writing each of this getter functions?
In PHP, for example, I would just use the magic method __call,
or pass as an argument with the list name and reference it dynamically.
Is there a way to do something similar in Java?
Or an alternative strategy to achieve the same result?
You should look into inheritance.
What you basically must do is define an interface (or extend a List class)
public interface ListTest{
//**Gets keys from lists*//
GetFromListOne(int key);
}
then
public class Listone implements ListTest{
/** methods **//
GetFromListOne(int key);
/** methods **//
}
Have fun extending
http://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html
You could use a 2 dimensional array, or a list of arrays and have your function take 2 parameters. One for the array that you want and the other for the element in the array.
2 dimensional array:
String[][] ListN = new String[100,100];
String getFromList(int n, int key) {
return ListN[n][key];
}
Or list of arrays:
List<String[]> listOfArrays = new ArrayList<String[]>();
listOfArrays.add(new String[100]);
listOfArrays.add(new String[100]);
String getFromList(int n, int key) {
return listOfArrays.get(n)[key];
}
Could you have a function that takes as input the key and the list number:
public String GetFromListOne(int list, int key) {
switch(list):
case 1:
return ListOne[key];
break;
case 2:
return ListTwo[key];
break;
...
}
or even better make an array of arrays:
String[][] ListOfLists = new String[10];
ListOfLists[0] = new String[100];
...
public String GetFromList(int list, int key) {
return ListOfLists[list][key];
}
Otherwise I don't know of a function to override like __call
String[] ListFour=new String[100];
String[] ListTwentyThree=new String[100];
String[] ListNine=new String[100];
String[] ListOne=new String[100];
Hashtable<Integer,String[]> yourlist=new Hashtable<Integer,String[]>();
yourlist.put(4, ListFour);
yourlist.put(23, ListTwentyThree);
yourlist.put(9, ListNine);
yourlist.put(1, ListOne);
System.out.println(yourlist.get(4)[5]);//fifth string in ListFour
System.out.println(yourlist.get(23)[51]);//fifty first string in List23
System.out.println(yourlist.get(9)[1]);//first stringin ListNine
another version:
Hashtable<Object,String[]> yourlist=new Hashtable<Object,String[]>();
yourlist.put("two multiplied by two", ListFour);
yourlist.put(23, ListTwentyThree);
yourlist.put(0.03, ListNine);
yourlist.put(true, ListOne);
System.out.println(yourlist.get("two multiplied by two")[5]);//fifth string in ListFour
System.out.println(yourlist.get(23)[51]);//fifty first string in List23
System.out.println(yourlist.get(true)[1]);//first stringin ListNine
Based in the __call PHP method, you can achieve this implementing a method that receives the list and the index, and using generics you can get something like this.
public class Utility {
public <T> T getElementFromArray(T[] array, int index) {
if (index >= array.length || index < 0) return null;
return array[index];
}
}
The pitfall of this method is that can't be used for primitive array holders, like int[]. The solution for these cases would be using the wrapper classes for primitive types.
public static void main(String[] args) {
Utility u = new Utility();
String[] ss = new String[2];
ss[0] = "Hello";
ss[1] = "world!";
System.out.println(u.getElementFromArray(ss, 0));
System.out.println(u.getElementFromArray(ss, 1));
int[] ii = new int[2];
ii[0] = 5;
System.out.println(u.getElementFromArray(ii, 0)); //compile error
//Solution: use wrapper classes
Integer[] ii2 = new Integer[2];
ii2[0] = 5;
System.out.println(u.getElementFromArray(ii2, 0));
}
Try this code
List<String[]> lists = new ArrayList<String[]>();
public String getFromLists(int key) {
List<String> res = new ArrayList<String>();
for (String[] s: lists){
res.add(s[key]);
}
return res.get(key);
}
or better
public String getFromLists(int key) {
return lists.get(key)[key];
}

Categories

Resources