How do I store these printed letters into an array? - java

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);
}
}
}

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

Need to find difference between two characters(Alphabet is cyclic)

Given a string, "azza". In this a-z = 25, z-z = 0, z-a = 25. But since alphabet is cyclic, I need 'a' just after 'z' i.e., in the above string z-a = 1.
For normal string where we dont encounter 'a' just after 'z', my code is this
class TestClass {
public static void main(String args[] ) throws Exception {
Scanner sc = new Scanner(System.in);
int i;
int t = sc.nextInt();
sc.nextLine();
for(i=0;i<t;i++)
{
String s =sc.nextLine();
char[] string =s.toCharArray();
for(i=0;i<string.length;i++)
{
if((string[i]-string[i+1])==1 || (string[i]-string[i+1])==-1)
{
System.out.println("1");
}
}
}
}
}
First, reverse subtractions: when you need to compute z-a in your scheme, compute 'a'-'z' and vice versa.
This way you can sometimes arrive at a negative result. When this happens, add 26 to it. This would act as "circling back" to the beginning.
char first = 'a';
char last = 'z';
int diff = first - last; // negative 25
if (diff < 0) {
diff += 26;
}
Demo.

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);
}
}

pass array names as parameter in class method

// 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.

Count letters in a string Java

I'm doing an assignment where I'll have to code a program to read in a string from user and print out the letters in the string with number of occurrences. E.g. "Hello world" in which it should print out "h=1 e=1 l=3 o=2 ... etc.", but mine only write "hello world" and the amount of letters in total. I can't use the hashmap function, only arrays. Can someone give me a hint or two on how to proceed from the written code below to get my preferred function? I don't understand exactly how to save the written input in array.
Here's my code so far.
public class CountLetters {
public static void main( String[] args ) {
String input = JOptionPane.showInputDialog("Write a sentence." );
int amount = 0;
String output = "Amount of letters:\n";
for ( int i = 0; i < input.length(); i++ ) {
char letter = input.charAt(i);
amount++;
output = input;
}
output += "\n" + amount;
JOptionPane.showMessageDialog( null, output,
"Letters", JOptionPane.PLAIN_MESSAGE );
}
}
You don't need 26 switch cases. Just use simple code to count letter:
String input = userInput.toLowerCase();// Make your input toLowerCase.
int[] alphabetArray = new int[26];
for ( int i = 0; i < input.length(); i++ ) {
char ch= input.charAt(i);
int value = (int) ch;
if (value >= 97 && value <= 122){
alphabetArray[ch-'a']++;
}
}
After done count operation, than show your result as:
for (int i = 0; i < alphabetArray.length; i++) {
if(alphabetArray[i]>0){
char ch = (char) (i+97);
System.out.println(ch +" : "+alphabetArray[i]); //Show the result.
}
}
Create an integer array of length 26.
Iterate each character of the string, incrementing the value stored in the array associated with each character.
The index in the array for each character is calculated by x - 'a' for lower case characters and x - 'A' for upper case characters, where x is the particular character.
You can create an Array which first element will represent 'a', second 'b', etc. If you need distinction between lower and upper cases than you can add it at the end. This array will have all values equals 0 at the beginning.
Then you iterate through your sentence and you increment required values on the array.
At the end you print all values that are > 0. Simple?
Let me know if you need more help
No you should not create an array of 26. This will break if the string contains unexpected characters. (ä, ö, ü anyone?)
As I pointed out im my comment use a Map. This will work forr all posible characters out there.
import java.io.*;
public class CharCount {
public static void main(String[] args) throws IOException
{
int i,j=0,repeat=0;
String output="",input;
char c=' ';
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter name ");
input=br.readLine();
System.out.println("entered String ->\""+input+"\"");
input=input.toLowerCase();
for(i=0;i<input.length();i++)
{
for(j=0;j<output.length();j++)
{
if(input.charAt(i)==output.charAt(j) || input.charAt(i)==c)
{
repeat=1;
break;
}
}
if(repeat!=1)
{
output=output+input.charAt(i);
}
repeat=0;
}
System.out.println("non-reepeated chars in name ->\""+output+"\"");
int count[]=new int[output.length()];
for(i=0;i<output.length();i++)
{
for(j=0;j<input.length();j++)
{
if(output.charAt(i)==input.charAt(j))
count[i]=count[i]+1;
}
}
for(i=0;i<output.length();i++)
System.out.println(output.charAt(i)+"- "+count[i]);
}
}

Categories

Resources