Java, multiple letters assigned to one variable - java

I'm working on a while-loop which should check a text and see if letters are in CAPS or not as well as if they are vowels etc. I'm not sure of how to create a variable which can store certain letters. I asked this question yesterday an was told to use Array, but im wondering theres anyway to do this with help of Strings,charAt.

You can do this without a loop :-
String s = "HELLO";
if(s.toUpperCase().equals(s)){
System.out.println("String is All-CAPS!");
}

Yes you can just iterate over the String with charAt() for every position. If you have a String text:
for(int i = 0; i < text.length() ; i++){
char currentChar = text.charAt(i);
doSomething(currentChar);
}

Related

How to set array length to the size of a string and bring in characters from the string in Java

Hi I am new to Java and am working on a project to get a string split up into individual characters and sent to JavaFX. I imagine the best way is to create an Array for this.
I want to create the array so it has an index of at least the the length of the string and I am getting an error. I then want to send part of the string from a certain point to the end of it to the array. I imagine then I can send the individual letters to JavaFX labels and boxes.
public static void main(String[]args) {
String gamePhrase = "Some Phrase here";
String guessPhrase = gamePhrase.replaceAll("[a-zA-Z0-9]", "*");
System.out.println(guessPhrase);
System.out.println(arraytest);
char[] array2 =new char[gamePhrase.length()];
guessPhrase.getChars (1,gamePhrase.length(),array2,0);
System.out.println(array2);}
}
Where am i going wrong in this ? Why cant I use the the string.length() feature?
Is there are better way any one could suggest? I dont want to use the toArray as the array will not contain all characters.
Any help would be much appreciated.
You can use the string .toCharArray().
char[] array2=gamePhrase.toCharArray()
Then you will have the same as getChars for all the string.
I hope this code will help you.,
String str = "hello";
char[] ch = new char[str.length()];
ch = str.toCharArray();
for(int i=0;i<ch.length;i++){
//this will print all the char
System.out.println("ch len == "+ ch[i]);
//to select specific char
if(ch[i] == 'l'){
System.out.println("selected chars == "+ ch[i]);
}
}

Length of an array that was initialized using a split string?

I have the following code to split a String of a list of words separated by spaces. The string is split and used to populate the array. If I use the .length method, will it return the amount of split strings? As in, would it be similar to the String.length method that counts the amount of characters and returns that value?
I want to have the program increment the array position by one each time it's run, but I want it to reset to 0 if it already used the last word, so it circles back and starts with the first word again.
Would this bit of code reset the word position to 0 when it has already used the last word in the array?
String wordsList[] = words.split(" ");
this.currentWord = wordsList[wordPos];
if(wordPos < wordsList.length)
wordPos++;
else
wordPos = 0;
If you use array.length on an array doesn't it tell you what the length is?
The answer is yes. Also, the .length is a property and not a method.
Take a look at this going over the .length property with a bit more detail. Cheers.
If I understand correctly, It sounds like you want to use a for loop like this?:
String words = "Blah blarg bloob"
String wordsList[] = words.split(" ");
String currentWord = "";
for (int i = 0; i < wordsList.length; i++){
if (currentWord !=null && currentWord.equals(wordsList[i])) {i = 0;}
currentWord = wordsList[i];
}

java regex replace any double letter in word with single

I've been searching for hours but can't find an answer, I apologize if this has been answered before.
I'm trying to check each word in a message for any double letters and remove the extra letter, words like wall or doll for example would become wal or dol. the purpose is for a fake language translation for a game, so far I've gottan as far as identifying the double letters but don't know how to replace them.
here's my code so far:
public String[] removeDouble(String[] words){
Pattern pattern = Pattern.compile("(\\w)\\1+");
for (int i = 0; i < words.length; i++){
Matcher matcher = pattern.matcher(words[i]);
if (matcher.find()){
words[i].replaceAll("what to replace with?");
}
}
return words;
}
You can do the whole replacement operation in one statement if you use back references:
for (int i = 0; i < words.length; i++)
words[i] = words[i].replaceAll("(.)\\1", "$1");
Note that you must assign the value returned from string methods that (appear to) change strings, because they return new strings rather than mutate the string.
String.replaceAll does not modify the string in-place. (Java String is immutable) You need assign the returned value back.
And the String.replaceAll accepts two parameters.
Replace following line:
words[i].replaceAll("what to replace with?");
with:
words[i] = "what to replace with?";

Is there a way to remove characters from a string? Java

I am having trouble removing letters from a string. String ALPHABET = "abcdefghjklmnopqrstuvwxyz"; User puts in a string. "klmn". How would i remove klmn from the alphabet? Is there a way? Other then putting it into an array?
This is what i started with. This only removes the last letter in the string. Whats my problem here.
for(int i = 0; i < message.length(); i++){
for(int j = 0; j < ALPHABET.length(); j++){
letter = message.charAt(i);
if(ALPHABET.charAt(j) == message.charAt(i)){
newALPHABET = ALPHABET.replace(letter, ' ');
}
}
}
Don't know what you want to do but you can use String#replace
String alphabet = "abcdefghjklmnopqrstuvwxyz";
alphabet = alphabet.replace("klmn","");
Write a method to delete it.. the logic here is replace the char you want to delete with the next char.. and in place of second one keep the third char and so on..
if you want to delete a large length of String..
then use the method Replace..
You can do that with regular expressions. Try the next:
static String ALPHABET = "abcdefghjklmnopqrstuvwxyz";
public static void main(String[] args) {
String input = JOptionPane.showInputDialog("Letters: ");
Pattern p = Pattern.compile("[" + Pattern.quote(input) +"]");
Matcher m = p.matcher(ALPHABET);
String result = m.replaceAll("");
System.out.println(result);
}
If you simply wanted to replace a character or simple substring, then String.replace is the solution.
If you wanted to replace matches a regex, then String.replaceAll is the the solution.
The reason your code is not working is because there are a couple of bugs in it:
You appear to be under the impression that String.replace(char, char) replaces a single character instance. In fact, it replaces all instance of the first character in the String.
Each loop iteration creates a new String and assigns it to newALPHABET. But then you start again with ALPHABET on the next iteration.
If the aim is to produce an "alphabet" that excludes the letters in message, then the correct solution is something like this:
for (int i = 0; i < message.length(); i++) {
ALPHABET = ALPHABET.replace(message.charAt(i), ' ');
}
... except that you should NOT use ALPHABET as the name of a variable. It should be alphabet!!!

JAVA: storing input into array

I need to write a program where the program would generate random letter and i would need to store this random character into an array
char[] arrayRandom = new char[10];
for (int i = 0; i < 8; i++) {
randomNumLet = (generator.nextInt(20) + 1);
System.out.print(arrayRandomLetter[randomNumLet] + " ");
arrayRandomLetter[randomNumLet] = arrayRandom[i];
}
is there anything wrong with my code?
because when i run this and printed the array i get boxes for all the values in the array and there are some letter that this line of code cannot print
System.out.print(arrayRandomLetter[randomNumLet] + " ");
Thanks
You're assigning an element of arrayRandomLetter a value from arrayRandom. As you never initialize arrayRandom, its values are all 0. 0 is not the value of a printable character, hence the boxes.
An easy way to pick a random character is like this:
String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char randomChar = chars.charAt(random.nextInt(chars.length()));
You are trying to print arrayRandomLetter before it is assigned.
I'm not going to give you the answer, but I will give you a hint:
(char)('A' + 1) is 'B'
#fastcodejava's answer explains why you are seeing "boxes" -- rendering the ASCII NUL character.
#Mark Peters is also correct, but that's not the simplest solution.

Categories

Resources