How to enter characters into a string array? - java

I'm trying to use a for loop to enter characters a-z into a string array, but I'm not having much luck converting characters to string values so they'll actually go into the string array. I keep getting null values as my output. Could anyone provide some tips on how to get characters into a string array?
This is what I have so far:
String[] letters = new String[26];
for (char ch = 'a'; ch <= 'z'; ch++)
{
int i = 0;
letters[i] = String.valueOf(ch);
i++;
}
System.out.println(Arrays.toString(letters));

String[] letters = new String[26];
int i = 0;
for (char ch = 'a'; ch <= 'z'; ch++)
{
letters[i] = String.valueOf(ch);
i++;
}
System.out.println(Arrays.toString(letters));
Try this. i=0 should be outside the loop.

Move int i = 0; outside the loop like Eran said or just don't use another counter but determine index by ordinal character representation:
String[] letters = new String[26];
for (char ch = 'a'; ch <= 'z'; ch++) {
int index = (int) ch - 97;
letters[index] = String.valueOf(ch);
}
System.out.println(Arrays.toString(letters));
Additionally, you don't have to use another local variable and could just do letters[(int) ch - 97] = ... of course.

your inserting each time to letters[0], keep Variable i outside the loop.
String[] letters = new String[26];
int i = 0;
for (char ch = 'a'; ch <= 'z'; ch++)
{
letters[i++] = String.valueOf(ch);
}
System.out.println(Arrays.toString(letters));

for (char ch = 'a'; ch <= 'z'; ch++){
int i = 0;
letters[i] = String.valueOf(ch);
i++;
}
You need to understand what it does : at EACH iteration you're initializing the variable i to 0 so you will never write in an other place than letters[0]
You need only to set it to 0, and then increment it, so just put the instruction before the loop
An other easy way would be only :
char[] letters = "abcdefghijklmnopqrstuvwxyz".toCharArray();

For your particular purpose, with Java 8 Streams, you don't even need a loop.
String[] letters = IntStream.rangeClosed('a', 'z').mapToObj(i -> Character.toString((char)i)).toArray(String[]::new);
System.out.println(Arrays.toString(letters));
To break it down:
IntStream.rangeClosed(int, int) makes a Stream of ints from the first int to the second, inclusive of both endpoints. We use this because there is no CharStream class (for some reason), but we can still use chars 'a' and 'z', which will be implicitly converted to their int value.
mapToObj takes a function which will convert each int of the Stream into an object. It gets a little messy here, as there is no single step conversion from int to String, we first need the int interpreted as a character value. So, we cast each int (named i) to a char, and then wrap that in a conversion from char to String: i -> Character.toString((char)i). This will leave us with a Stream<String>.
Now, we want the output to be String[], as per your question. Stream has a toArray method, but this will give us an annoying Object[] result. Instead, we will supply the method we want to have used to build the array. We don't want anything fancy, so we'll just use the standard initializer for a String array: toArray(String[]::new).
After that, letters will be equal to an array of Strings, and each one will successively be a letter from a to z.
If you don't have access to Java 8 or simply don't like the above solution, here's a simplified version of your above code that removes the need for the index:
String[] letters = new String[26];
for (char c = 'a'; c <= 'z'; c++) letters[c - 'a'] = Character.toString(c);
System.out.println(Arrays.toString(letters));
In Java, chars can be treated as ints because below the surface, they are both stored as numbers.

Related

Behavior of foreach when setting new chars in a String

I just read a question about chars and I had a doubt about it so I started to try some code... I'm trying to set all chars from a String one by one using a loop, I've tried with for and the "forEach" version of it, these are my tests:
String testString = "testing";
char[] array = testingString.toCharArray();
Then the loops:
for(int i = 0; i < array.length; i++) {
array[i] = 'x';
}
And this is the output for that loop: (the expected one)
"xxxxxxx"
But then I've tried with the another "for" format:
for(char c: array) {
c = 'x';
}
And it didn't work for me.. the output was the same String ("testing"). I'm misunderstanding the behavior of the for each? Why is the 2nd loop not working the same as the first one? I've used that loop format a lot of times but I can't understand why is not working in this case. I'm not familiar with the char type, maybe I'm missing something about it.
As documented in JLS ยง14.14.2. The enhanced for statement, the following loop:
for(char c: array) {
c = 'x';
}
is equivalent to the following basic for statement:
for (int #i = 0; #i < array.length; #i++) {
char c = array[#i];
c = 'x';
}
As you can see, changing c will not affect the array.
That's because you are edditing the character, not the corresponding charAt the inception String.
Probably, you should take the position of these char at the string and setting it up.

Setting each of the alphabet to a number

so I am trying to set each of the letter in the alphabet to a number like a = 1
b = 2 c =3 and so on.
int char = "a";
int[] num = new int{26};
for (int i = 0; i <num.length; i++){
System.out.print(i);
But after this i got Stuck so if you possible help me out. So when the users input a word like cat it would out put 3-1-20.
You can subtract 'a' from each char and add 1. E.g.
String input = "cat";
for (char c : input.toCharArray()) {
System.out.print(c - 'a' + 1);
}
The code you posted doesn't compile as you can't assign a String to an int and char is a reserved word (name of a primitive type)
int char = "a";
You also mention that you want the output formatted like this "3-1-20". This is one way to achieve that :
String input = "cat";
String[] out = new String[input.length()];
for (int i = 0; i < input.length(); ++i) {
out[i] = Integer.toString(input.charAt(i) - 'a' + 1);
}
System.out.println(String.join("-", out));
Both versions work only for lowercase English letters (a to z)
Assigning a number to a character is called an "encoding". As computers can only handle numbers internally, this happens all the time. Even this text here is encoded (probably into an encoding called "UTF-8") and then the resulting number is stored somewhere.
One very basic encoding is the so called ASCII (American Standard Code for Information Interchange). ASCII already does what you want, it assigns a number to each character, only that the number for "A" is 65 instead 1.
So, how does that help? We can assume that for the character A-z, the numeric value of a char is equal to the ASCII code (it's not true for every character, but for the most basic ones, it's good enough).
And this is why everyone here tells you to subtract 'A' or 'a': Your character is a char, which is a character, but also the numeric value of that character, so you can subtract 'A' (again, a char) and add 1:
'B' - 'A' + 1 = 2
because...
66 (numeric value of 'B') - 65 (numeric value of 'A') + 1 = 2
Actually, char is not ASCII, but UTF-8, but there it starts to get slightly bit more complex, so ASCII will suffice for the moment.
the best way of doing this is to convert the String to a byte[], like this:
char[] buffer = str.toCharArray();
Then each of the characters can be converted to their byte-value (which are constants for a certain encoding), like this:
byte[] b = new byte[buffer.length];
for (int i = 0; i < b.length; i++) {
b[i] = (byte) buffer[i];
}
Now look at the resulting values and subtract/add some value to get the desired results!

Replace entire char array with different char

I'm very new to programming and I've spent some time looking for a way to do this that I can understand. I'm making a hangman game in java, it's all text based, and I've got almost the entire thing done. All I need is to replace a character array that holds the value of a random word to be replaced with dashes. So if the word was "java" I need to change that character array to "----". Since the word is chosen at random from a list, I have to find a way to use the length of the word to apply those dashes, but I'm not sure how.
Any help is appreciated!
A simple way to replace all the characters by '_' would be :
char[] charArray = {'W','O','R','D'};
Arrays.fill(charArray, '_');
I will give you an example based on what you have provided so far with java and ----:
public class Program {
public static void main(String[] args) {
String value = "java";
char[] array = value.toCharArray();
// Convert string to a char array.
for(int i = 0; i < value.length(); i++)
{
array[i] = '-';
}
// Loop over chars in the array.
for (char c : array) {
System.out.print(c);
}
}
}
OK, a few things that may be helpful in solving this task:
If you have a String you can easily get the length of that String like this:
String word = "java";
int lengthOfWord = word.length();
You can easily edit the contents of an array by accessing the individual elements:
char[] array = new char[4];
array[0] = '-';
array[1] = '_';
array[2] = '-';
array[3] = '_';
If you want to do something repeatedly and know how often you want to do that, using a for-loop is often a great idea. And you can use the counter within the loop. So for example:
int sum = 0;
for(int i = 0; i < 10; i++) {
sum += i;
}
So, combine those pieces of information and you can replace every element of that array. :-)

How do I shift the value of my char array in java?

What I'm trying to do is create an encryption method that shifts a char array taken from an input file by a determined amount of letters. I'm having trouble figuring out how to change the chars into ints and back.
THis is what I've got so far:
char [] sChar = new char[line.length()];
for(int i = 0; i < sChar.length; i++){
String s = reader.next();
sChar = s.toCharArray();
if(Character.isLetter(sChar[i])) {
char c = 'a';
int b = c;
sChar[i] += key;
Not sure what you are thinking.
I thought conversion int to character and back would be easy.
Just to freshen up the idea I checked
char xdrf = 'a';
System.out.println((int)xdrf); // output is 97
int idrf= 99;
xdrf = (char)idrf;
System.out.println(xdrf); // output is c
also if you key is a character you can directly sum it therefore statement
schar[i] += key;
should be good
more to it
idrf = idrf + 'd';
System.out.println(idrf); //output is 199
further using
System.out.println(Character.getNumericValue(idrf-20)); //output is 3
this all is working by ascii value. I am unsure if you would like ascii values to be used.

Converting a lowercase char in a char array to an uppercase char (java)

Hello I am trying to write a little segment of code that checks if each char in a char array is lower case or uppercase. Right now it uses the char's ASCII number to check. After it checks it should convert the char to upper case if it is not already so:
for (int counter = 0; counter < charmessage.length; counter++) {
if (91 - charmessage[counter] <= 0 && 160 - charmessage[counter] != 0) {
charmessage[counter] = charmessage[counter].toUpperCase();
}
}
charmessage is already initialized previously in the program. The 160 part is to make sure it doesn't convert a space to uppercase. How do I get the .toUpperCase method to work?
I would do it this way. First check if the character is a letter and if it is lowercase. After this just use the Character.toUpperCase(char ch)
if(Character.isLetter(charmessage[counter]) && Character.isLowerCase(charmessage[counter])){
charmessage[counter] = Character.toUpperCase(charmessage[counter]);
}
You can use the Character#toUpperCase for that. Example:
char a = 'a';
char upperCase = Character.toUpperCase(a);
It has some limitations, though. It's very important you know that the world is aware of many more characters that can fit within the 16-bit range.
String s = "stackoverflow";
int stringLenght = s.length();
char arr[] = s.toCharArray();
for (int i = stringLenght - 1; i >= 0; i--) {
char a = (arr[i]);
char upperCase = Character.toUpperCase(a);
System.out.print(upperCase);
}

Categories

Resources