pass array names as parameter in class method - java

// My code is doing something; difficult to get.. still a concept can be grasped.
//I am having my method (searchCity) in class graph. this method is called from main
//class and is yes... selecting one array by charachter it is passed with
public class graph {
int a = 1000;
int flag = 0;
//array of all cities having elements as connection to other cities
public graph(){
char [] i = {'i','v'};
char [] v = {'v','u'};
char [] u = {'u','b','h'};
char [] b = {'b','p','f','u'};
char [] h = {'h','u','e'};
char [] e = {'e','h'};
char [] p = {'p','b','r','c'};
char [] c = {'c','p'};
char [] r = {'r','s','p'};
char [] s = {'s','f','r'};
char [] f = {'f','s','b'};
}
public void searchCity( char i, char j){
// check for equal array as parameter i (include must )
for (int z = 0 ; z < i.length; z ++) {
if (i[z] == 'j') {
int ascii = (int) 'j';
int flag = 1;
System.out.println(ascii);
}
else {
// checking for smallest cost in the complete array
int ascii = (int) i[z];
if(a>ascii)
a=ascii;
else continue;
}
}
if (flag==0){
char b = (char) a;
char [] c = {'b'};
}
searchCity(c, j);
}
I have a class with many arrays named in alphabets like char [] a, char [] b etc. I also have a method in class.
In main class I have created an object and if i need to pass two alphabets which will be like reference for calling only those arrays whose name are passed.
like my line of code in main class is as follows:
object.function(char1, char2);
these characters will be alphabets(a,b,c etc) can it be done ?? how ?? please help. I searched it but exact problem is not answered.. Regards

If you are asking how to pass char arrays to a function, all you need to do is set up your function as follows:
public static void MyFunction(char[] a, char[] b) {
//do stuff to char arrays
}
Then when you call the function, you will be able to pass them in with:
char[] a = {'a', 'b', 'c'};
char[] b = {'d', 'e', 'f'};
MyObject.MyFunction(a, b);
It would be helpful if you posted your current code so I can tell exactly what it is you're trying to do, though.
EDIT:
If you want to be able to call the arrays with a char, I'd suggest containing them in a HashMap:
Map<Character, Character[]> graph = new HashMap<Character, Character[]>();
graph.put('i', new Character[] {'i', 'v'});
graph.put('v', new Character[] {'v', 'u'});
graph.put('u', new Character[] {'u', 'b', 'h'});
// etc.
Then you can call the arrays as follows:
System.out.println(graph.get('i')[0]); // Prints 'i'
System.out.println(graph.get('i')[1]); // Prints 'v'
System.out.println(graph.get('i').length); // Prints '2'
So a function could be something like this:
public static void MyFunction(char a, char b) {
graph.get(a)[0]; // grab first character in array
for (int i=0; i<graph.get(b).length; i++) {
// recursively go through array with graph.get(b)[i]
}
}
Demonstration Here
Hope this helps.

I found your question kind of confusing, so if I am way off, please tell me.
However, what I think your trying to do is is call a char array with a character. For instance calling the char array c with the character 'a'. You can do this with if conditionals of switches. Also, what does your object.function(char1, char2) actually do? That would help me out in answering you question.

Related

Populating Multidimensional Arrays in Java

So I am trying to populate a 2D array from two strings, as seen below.
However, when I go to compile my code, I get a
"java: incompatible types: char[] cannot be converted to char"
error. What am I doing wrong?
public static void main(String[] args) {
String alphabet = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
String iAlphabet = ("ZYXWVUTSRQPONMLKJIHGFEDCBA");
char alphabetArray [][] = {{alphabet.toCharArray()},{iAlphabet.toCharArray()}};
System.out.print(alphabetArray[4][4]);
}
}
(New to Java, and am just bashing my head against a wall on this one)
I guess you want to be able to translate the character from one string to the other one at the same position:
public static void main(String[] args) {
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String iAlphabet = "ZYXWVUTSRQPONMLKJIHGFEDCBA";
char alphabetArray [][] = {alphabet.toCharArray(),iAlphabet.toCharArray()};
System.out.print("3rd character: " + alphabetArray[0][2] + " -> " + alphabetArray[1][2]);
}
This prints:
3rd character: C -> X
An example of ussage as translate would be:
public static void main(String[] args) {
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String iAlphabet = "ZYXWVUTSRQPONMLKJIHGFEDCBA";
char alphabetArray [][] = {alphabet.toCharArray(),iAlphabet.toCharArray()};
String test = "HELLO WORLD";
StringBuffer translated = new StringBuffer();
for (int i = 0; i < test.length(); i++) {
int index = alphabet.indexOf(test.charAt(i));
if (index > 0) {
translated.append(alphabetArray[1][index]);
} else {
translated.append(test.charAt(i));
}
}
System.out.println("original sentence: " + test);
System.out.println("translated sentence: " + translated.toString());
}
which prints:
original sentence: HELLO WORLD
translated sentence: SVOOL DLIOW
Declare the arrays as shown below. And remember it's not a 26 x 26 array. It is a 2 x 26 array.
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String iAlphabet = "ZYXWVUTSRQPONMLKJIHGFEDCBA";
char alphabetArray [][] = {alphabet.toCharArray(),iAlphabet.toCharArray()};
Print V from the second.
System.out.print(alphabetArray[1][4]);
Print E from the first.
System.out.print(alphabetArray[0][4]);
You are putting an array of char where you need to place the only char. So remove the curly braces and simply put an array of char
Your Code should be like this
public static void main(String[] args) {
String alphabet = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
String iAlphabet = ("ZYXWVUTSRQPONMLKJIHGFEDCBA");
char[] charArray = alphabet.toCharArray();
char[] charArray2 = iAlphabet.toCharArray();
char alphabetArray[][] = { charArray, charArray2 };
System.out.println(alphabetArray[0][23]);
}
you could also take advantage of the fact that the letters 'A'-'Z' are in order
for example: if you want to translate a number to a letter in the alphabet you can just say
char a = 'A';
a+=num;
or if you want it to go backwards
char a = 'Z';
a-=num;
num being the equivelent index you would've given.
this is assuming that you want to make the array read-only of course, and some sort of validation before performing these operations would be recommended. (Verifying the number is positive and less than 26)
if this works in your case, then that's great.
If you want to do a ceaser cipher: IE translate any character by any offset, you can do the following:
private static char offsetChar(char chr, int offset){
chr = Character.toUpperCase(chr);
//value from 0-25 representing letter
int val = chr - 'A';
//make sure that the offset doesn't make it overflow past 26
val = (val + offset) % 26;
// convert back to letter from number 0-25
return (char)('A' + val);
}
also note that this will auto-capitalize the letter, if you don't want that to happen you can test if it is uppercase and return it in the correct state at the end using
Character.isUpperCase and Character.toUpperCase and Character.toLowerCase

Comparing if a string's character exist in an array of characters

I want the user to input a string, then I want to check if each charachter in this string exists in an array of charachters I created. Even if it's not in the correct order.
The way I go about it is initialise the array of chars then through using the scanner have a String input from the user.
public static char[]aa={'A','C','D','E','F','G','H','I','K','L','M','N','P','Q','R','S','T','V','W','Y','U','O','B','J','Z','X'};
I created a function
private static void isValidSequence(String sequence, char[] k) {
outter :for (int j = 0; j < sequence.length(); j++) {
for (int i = 0; i < k.length; i++) {
if(sequence.charAt(j) == k[i]){
break;
} else {
System.out.println("invalid");
break outter;
}
}
}
}
What happens is that if for example the first letter of the the string doesn't match the first input of array it gives me an 'invalid' input. How can I go around that? and make it iterate through the whole array of characters before giving the invalid output.
An approach would be to sort your array, and then use the Binary Search Algorithm (BSA):
// sort the array once
Arrays.sort(aa);
// iterate over the input string
for(int i = 0, length = sequence.length(); i < length; i++) {
// the java implementation of the BSA returns negative numbers for not found elements
if(Arrays.binarySearch(aa, sequence.charAt(i)) < 0) {
// char was not found, break loop
return;
}
}
Note: If the array is not sorted / can not be sorted, then the BSA is useless and will produce undefined results.
Note 2: The BSA is faster (O(log n)) than simple iteration (O(n))
This can also be done as below :
char[]aa={'A','C','D','E','F','G','H','I','K','L','M','N','P','Q','R','S','T','V','W','Y','U','O','B','J','Z','X'};
String s = "aStrinG";
for (char c : s.toCharArray()) {
for (char c2 : aa) {
if (c2 == c) {
System.out.println("String char " + c + " exists in char array");
}
}
}
It produces :
String char S exists in char array
String char G exists in char array
Best way is to use SET instead of an Array. A set contains no duplicate elements and then simply you can use it using the method contains()
Using Java 9 (Unmodifiable Sets)
Set<Character> alphabetSet = Set.of('A', 'B', 'C');
//Another way
//Set<Character> alphabetSet = new HashSet<>(Arrays.asList('A', 'B', 'C'));
for(char c: sequence)
{
if(alphabetSet.contains(c)){
//do something
}
else{
//do something
}
}
Read more about Set:
https://docs.oracle.com/javase/7/docs/api/java/util/Set.html
To directly answer your question:
Solution 1:
Use continue instead of break this will print "invalid" each time a character is not in k.
Solution 2:
You can use a counter and increment it every time you have a character not in k, then outside the loop you will have visibility on how many invalid characters you have.
Solution 3:
If you want even more detail you can have a list of characters and add each invalid character to this list. This will give you visibility on exactly what characters are invalid.
I am not sure what you are trying to do so I don't know which method is better for you, you can also use an altogether approach using streams for example.
If you start using the Collection provided, you could use a Set to do your checks.
First, convert the array into the Set :
char[] array = "abcdefghijklmnopqrstuvwxyz".toCharArray();
Set<Character> setAllowed = new TreeSet<>();
for(char c : array){
setAllowed.add(c);
}
Then, you just have to iterate and check for each character. I would add another Set to retrieve every characters not allowed, giving a better output.
Set<Character> setError = new TreeSet<>();
for(char c : s.toCharArray()){
if(setAllowed.contains(c)){
setError.add(c);
}
}
Test :
public static void main(String[] args) {
String s = "foobar123";
char[] array = "abcdefghijklmnopqrstuvwxyz".toCharArray();
//INIT
Set<Character> setAllowed = new TreeSet<>();
Set<Character> setError = new TreeSet<>();
for(char c : array){
setAllowed .add(c);
}
//RESEARCH
for(char c : s.toCharArray()){
if(setAllowed.contains(c)){
setError.add(c);
}
}
//OUTPUT
System.out.println(setError);
}
[1, 2, 3]

How do I store these printed letters into an array?

Right now this program prints out the alphabet (a-z) however I want to take those letters and store each one in the array called leta, how do i do that?
public class Arrayofhope {
public static void main (String[]args) {
char []leta = new char[26];
char letter = (char)65;
char lettter=(char)90;
for (int i = letter;i<=lettter;i++ ) {
System.out.print((char)i);
}
}
}
This is almost a "syntax" type question, but it's also tricky enough that there's some value to pointing out how it works.
class Arrayofhope
{
public static void main( String[] args )
{
char[] leta = new char[ 26 ];
char letterA = 'a';
char letterZ = 'z';
for( int i = letterA; i <= letterZ; i++ ) {
System.out.print( (char) i );
leta[i-'a'] = (char)i;
}
}
}
Characters in single quotes are the same as integers of type char. You can assign them and do math on them. I think this makes the initial assignment of char letterA = 'a'; more clear than using the number 65.
And as mentioned you can do math with character types too. Note the aray index [i-'a'] is calculated so that 65 is subtracted from 65 for the first character, so that 'a' is stored in index 0, and proceeding up from there. This is kinda tricky but in the long run more clear, I think, and also easier than trying to program with an ASCII table in front of you.
public class Arrayofhope {
public static void main (String[]args) {
char []leta = new char[26];
char letter = (char)65;
char lettter=(char)90;
for (int i = letter,j=0;i<=lettter;i++,j++ ) {
let[j] = (char)i;
// If you don't want new variable you can do like below
let[i-65] = (char) i;
System.out.print((char)i);
}
}
}

Java Method for removing duplicates from char array

I have a char array filled by the user (arrayInput[]) with some characters, like {b, d, a, b, f, a, g, a, a, f}, and I need to create a method which returns a new char array with only the first occurrence of the character, but in the order of input. The book also says "A way to solve this problem is to create a boolean array to keep track of the characters to mantain!", but I can't imagine how the boolean array should work with the other arrays.
The main problem is that I can save in a boolean array if arrayInput contains a specific character, and even how many times, but only creating a very long ramified if-else into a for, like
if ((arrayOutput[i] == 'A') && (arrayControl[0] = false)) {
arrayControl[0] = true; }
where arrayOutput is the array I want to return from the method, arrayControl[0] is the value of 'A' in my boolean array I created into the method. A = 0, B = 1, ... Z = 25, a = 26, b = 27, ... 51 = z. For every single character, uppercase and lowercase, I created a place into the array, so I could check everything, but now I can't go any further. I don't know how to save the characters on arrayOutput, how to check if a character is already on arrayOutput and if it's already there, the array passes that specific character and go to the next one.
Also please remember I'm a newbie, so I know very little about Java. Please explain yourself the best you can. Thanks in advance!
This could work:
public static void main(String[] args) {
Main main = new Main();
char[] array = {'e','a','b','a','c','d','b','d','c','e'};
main.getCharArray(array);
}
private char[] getCharArray(char[] array) {
String _array = "";
for(int i = 0; i < array.length; i++) {
if(_array.indexOf(array[i]) == -1) // check if a char already exist, if not exist then return -1
_array = _array+array[i]; // add new char
}
return _array.toCharArray();
}
Output:
eabcd
boolean arr[26]; //considering only small letters arrive. otherwise take a larger array.
for( i=0;i<str.length;i++ )
arr[str[i]-'a']=true;
The ones at last after the loop are true are the actual character. (all duplicates eleminated).
To take into consideration the positions,
int arr[26];
//initialize all the array elemnts to 0
for( i=0;i<str.length();i++ )
if(i>=arr[str[i]-'a'])
arr[str[i]-'a']=i+1;
//Those greater than 0 are non-duplicated characters. Their poistion of first occurence= (arr[i]-1)
EDIT: I have last used java almost a year ago. The algorithm is shown properly. Sorry for my awkward java code.
This might help. Make a separate array and store only non-duplicate characters.
char[] removeDuplicates (char[] arrayInput) {
boolean exists[]=new boolean[26];
char arrayOutput[] = new char[26];
int ctr=0;
for(int i=0; i<26; i++) {
exists[i] = false;
}
for(int i=0; i<arrayInput.length; i++) {
if(!exists[arrayInput[i]-97]) {
exists[arrayInput[i]-97]=true;
arrayOutput[ctr++]=arrayInput[i];
}
}
return Arrays.copyOfRange(arrayOutput, 0, ctr);
}
If you consider using of collection framework then it would be much easier. Your array of char with duplicate is arrayInput. Now put each char from it to a HashSet like this -
HashSet<Character> uniqueCharSet = new HashSet<Character>();
for(char each : arrayInput){
uniqueCharSet.add(each);
}
Now the HashSet uniqueCharSet will contains only the unique characters from the char array arrayInput. Note here all element in uniqueCharSet are wrapper type - Character.
You can convert the HashSet uniqueCharSet to array of Character like this -
Object[] uniqueCharArray = uniqueCharSet.toArray();
And then you can use them like this -
for(Object each : uniqueCharArray){
Character c = (Character) each;
System.out.println(c);
}
Here's the method to achieve what you need:
public static void main(String[] args) {
char[] arr= {'A','B','C','A','B'};
HashSet<Character> hset=new HashSet<Character>();
for(int i=0;i<arr.length;i++) {
hset.add(arr[i]);
}
Object[] ObjChar=hset.toArray();
char[] resultArr = new char[ObjChar.length];
for(int j=0;j<ObjChar.length;j++) {
resultArr[j]=(char) ObjChar[j];
}
for(char eachChar: resultArr) {
System.out.println(eachChar);
}
}

How to find the index of an element in an array in Java?

I am looking to find the index of a given element, knowing its contents, in Java.
I tried the following example, which does not work:
class masi {
public static void main( String[] args ) {
char[] list = {'m', 'e', 'y'};
// should print 1
System.out.println(list[] == "e");
}
}
Can anyone please explain what is wrong with this and what I need to do to fix it?
In this case, you could create e new String from your array of chars and then do an indeoxOf("e") on that String:
System.out.println(new String(list).indexOf("e"));
But in other cases of primitive data types, you'll have to iterate over it.
Alternatively, you can use Commons Lang ArrayUtils class:
int[] arr = new int{3, 5, 1, 4, 2};
int indexOfTwo = ArrayUtils.indexOf(arr, 2);
There are overloaded variants of indexOf() method for different array types.
For primitive arrays
Starting with Java 8, the general purpose solution for a primitive array arr, and a value to search val, is:
public static int indexOf(char[] arr, char val) {
return IntStream.range(0, arr.length).filter(i -> arr[i] == val).findFirst().orElse(-1);
}
This code creates a stream over the indexes of the array with IntStream.range, filters the indexes to keep only those where the array's element at that index is equal to the value searched and finally keeps the first one matched with findFirst. findFirst returns an OptionalInt, as it is possible that no matching indexes were found. So we invoke orElse(-1) to either return the value found or -1 if none were found.
Overloads can be added for int[], long[], etc. The body of the method will remain the same.
For Object arrays
For object arrays, like String[], we could use the same idea and have the filtering step using the equals method, or Objects.equals to consider two null elements equal, instead of ==.
But we can do it in a simpler manner with:
public static <T> int indexOf(T[] arr, T val) {
return Arrays.asList(arr).indexOf(val);
}
This creates a list wrapper for the input array using Arrays.asList and searches the index of the element with indexOf.
This solution does not work for primitive arrays, as shown here: a primitive array like int[] is not an Object[] but an Object; as such, invoking asList on it creates a list of a single element, which is the given array, not a list of the elements of the array.
That's not even valid syntax. And you're trying to compare to a string. For arrays you would have to walk the array yourself:
public class T {
public static void main( String args[] ) {
char[] list = {'m', 'e', 'y'};
int index = -1;
for (int i = 0; (i < list.length) && (index == -1); i++) {
if (list[i] == 'e') {
index = i;
}
}
System.out.println(index);
}
}
If you are using a collection, such as ArrayList<Character> you can also use the indexOf() method:
ArrayList<Character> list = new ArrayList<Character>();
list.add('m');
list.add('e');
list.add('y');
System.out.println(list.indexOf('e'));
There is also the Arrays class which shortens above code:
List list = Arrays.asList(new Character[] { 'm', 'e', 'y' });
System.out.println(list.indexOf('e'));
I believe the only sanest way to do this is to manually iterate through the array.
for (int i = 0; i < list.length; i++) {
if (list[i] == 'e') {
System.out.println(i);
break;
}
}
Simplest solution:
Convert array to list and you can get position of an element.
List<String> abcd = Arrays.asList(yourArray);
int i = abcd.indexOf("abcd");
Other solution, you can iterator array:
int position = 0;
for (String obj : yourArray) {
if (obj.equals("abcd") {
return position;
}
position += 1;
}
//OR
for (int i = 0; i < yourArray.length; i++) {
if (obj.equals("abcd") {
return i;
}
}
The problem with your code is that when you do
list[] == "e"
you're asking if the array object (not the contents) is equal to the string "e", which is clearly not the case.
You'll want to iterate over the contents in order to do the check you want:
for(String element : list) {
if (element.equals("e")) {
// do something here
}
}
This way should work, change "char" to "Character":
public static void main(String[] args){
Character[] list = {'m', 'e', 'y'};
System.out.println(Arrays.asList(list).indexOf('e')); // print "1"
}
Now it does print 1
class Masi {
public static void main( String [] args ) {
char [] list = { 'm', 'e', 'y' };
// Prints 1
System.out.println( indexOf( 'e', list ) );
}
private static int indexOf( char c , char [] arr ) {
for( int i = 0 ; i < arr.length ; i++ ) {
if( arr[i] == c ) {
return i;
}
}
return -1;
}
}
Bear in mind that
"e"
is an string object literal ( which represents an string object that is )
While
'e'
Is a character literal ( which represents a character primitive datatype )
Even when
list[]
Would be valid Java ( which is not ) comparing the a character element with a string element would return false anyway.
Just use that indexOf string function and you could find any character within any alphabet ( or array of characters )
If the initial order of elements isn't really important, you could just sort the array, then binarySearch it:
import java.util.Arrays;
class masi {
public static void main( String[] args ) {
char[] list = {'m', 'e', 'y'};
Arrays.sort(list);
// should print 0, as e is now sorted to the beginning
// returns negative number if the result isn't found
System.out.println( Arrays.binarySearch(list, 'e') );
}
}
Very Heavily Edited. I think either you want this:
class CharStorage {
/** set offset to 1 if you want b=1, o=2, y=3 instead of b=0... */
private final int offset=0;
private int array[]=new int[26];
/** Call this with up to 26 characters to initialize the array. For
* instance, if you pass "boy" it will init to b=0,o=1,y=2.
*/
void init(String s) {
for(int i=0;i<s.length;i++)
store(s.charAt(i)-'a' + offset,i);
}
void store(char ch, int value) {
if(ch < 'a' || ch > 'z') throw new IllegalArgumentException();
array[ch-'a']=value;
}
int get(char ch) {
if(ch < 'a' || ch > 'z') throw new IllegalArgumentException();
return array[ch-'a'];
}
}
(Note that you may have to adjust the init method if you want to use 1-26 instead of 0-25)
or you want this:
int getLetterPossitionInAlphabet(char c) {
return c - 'a' + 1
}
The second is if you always want a=1, z=26. The first will let you put in a string like "qwerty" and assign q=0, w=1, e=2, r=3...
here is another example and how indexOf is working.
public int indexOf(Object target) {
for (int i = 0; i < array.length; i++) {
if (equals(target, array[i])) {
return i;
}
}
return -1;
}
I am providing the proper method to do this one
/**
* Method to get the index of the given item from the list
* #param stringArray
* #param name
* #return index of the item if item exists else return -1
*/
public static int getIndexOfItemInArray(String[] stringArray, String name) {
if (stringArray != null && stringArray.length > 0) {
ArrayList<String> list = new ArrayList<String>(Arrays.asList(stringArray));
int index = list.indexOf(name);
list.clear();
return index;
}
return -1;
}
This way you can use upto 'N' letters.
char[] a={ 'a', 'b', 'c', 'd', 'e' };
int indexOf=0;
for(int i=0;i<a.length;i++){
if(a[i] != 'b'){
indexOf++;
}else{
System.out.println("index of given: "+indexOf);
}}
int i = 0;
int count = 1;
while ('e'!= list[i] ) {
i++;
count++;
}
System.out.println(count);

Categories

Resources