For some reason this code doesn't work.
public void actionPerformed(ActionEvent e) {
Random random = new Random();
int randomChar = random.nextInt((23 - 0) + 1);
for(int x = 23;x > 0;x-- ) {
String text;
text = original.getText();
text = text.toLowerCase();
text = text.replace(alphabet[x], alphabet[randomChar]);
newText.setText(text);
}
Just to clear a couple things up original and newText are JTextField, and alphabet is a char array with a-z.
Now when I run this it should go through and replace every character with a random one, starting at Z and ending at A however it just gives me the exact same string that I entered back, just converted to lowercase.
It's worth noting that if I replace
text = text.replace(alphabet[x], alphabet[randomChar]);
With
text = text.replace(alphabet[0], alphabet[randomChar]);
And put a bunch of A's into the input box it does change them into a random letter. EG:
aaaa input
llll output
or gggg output
it just doesn't work if I have a variable in there.
The rest of the code isn't important by the way, it's all declaring variables and setting up the GUI.
Any help is much appreciated!
In addition to moving the random character generation inside the loop (as suggested by #CIsForCoocckies), you'll also need to move the getText() and setText() calls outside the loop (because each time the loop is run, you start over with the original text so at most one kind of character would be replaced in the end, no matter how many times the loop iterates.
your randomchar is set before the loop with some char and then all chars are replaced to said char so - "yourstring" becomes "xxxxxxxxxx" where x=randomchar
In addition to the two other answers, I'd like to add a comment to the for loop:
for(int x = 23;x > 0;x--)
You won't enter the loop when x == 0 at all, which means the first char in your alphabet array won't be considered for replacement.
If you have the alphabet array already and want to replace every character with a random one, why not consider using:
for (int x = 0; x < alphabet.length; x++){
//your code here
}
This should be better than hard-coding
Related
I've got some String, and I'd like to replace some chars in it. Everything was running fine until the String hasn't two or more same chars, the program just replacing the first one, and I'm not able to change the second one.
StringBuilder userTitleBuilder = new StringBuilder(conversedTitle);
while (score>1) {
userLetter = userInput.next().charAt(0);
if (movieTitle.contains(String.valueOf(userLetter))) {
charIndex = movieTitle.indexOf(userLetter);
userTitleBuilder.replace(charIndex,userTitleBuilder.length(), String.valueOf(userLetter));
System.out.println(userTitleBuilder);
} else {
--score;
System.out.println("Wrong\nTries left "+score);
}
}
Here's the explanation of this code:
User from the start the program has a score equals to 10. userLetter it's just a char that will get some letter from the user, then if statement checking if movieTitle variable has char equals to that user just entered, if yes, charIndex will have it position (but it contains only first index, what if in word are more same letters?) now userTitleBuilder replace the chars in string that has that many "_" that movieTitle lenght, it's just covering the title.
*movieTitle and userTitleBuilder has the same value = "CocaCola"
I'd like to not get ready solution. I'd like to have some kind of hint, how do I replace more than one same character in String
A method called String.replace("old","new") can be used.
Follow this doc.
There is a string "hello-world!". Any character except A-Z and a-z has to stay in the same place, but letters have to be reversed. So, output would be "dlrow-olleh!".
I used string builder to design the solution, but I am curious if a string of length 12 can be declared and its characters filled in indices 5 and 11, then fill remaining with reversed letters.
Any other techniques or ideas to perform the same would be appreciated.
StringBuilder sb = new StringBuilder();
for(int i=S.length()-1; i >= 0; i--) {
String c = ""+S.charAt(i);
if(c.matches("[A-Za-z]")) {
sb.append(c);
}
}
for(int i = 0; i < S.length(); i++) {
String c = ""+S.charAt(i);
if(!c.matches("[A-Za-z]"))
sb.insert(i,c);
}
I got the output this way, but is there any way to use String here instead of StringBuilder?
You can't use String in the way you suggest, because String is immutable.
Another option, instead of StringBuilder, is to use a raw array of char. You know that the resultant string will have the same length as the source string, so you can do it like this:
Create an array using String.toCharArray.
Iterate from both ends simultaneously using indices i and j. Start index i from 0 moving forwards, and j from array length - 1, moving backwards.
Check the elements at i and j for a letter using Character.isLetter. If it's not a letter, just skip it by advancing i forwards or j backwards.
Swap the array elements at i and j.
Repeat while i < j.
Create the new string using new String(charArray)
As this looks like an exercise, I'll leave the actual coding to you.
Caveat: the above only works for strings where the Unicode code points are in the Basic Multilingual Plane (i.e. most strings to you and me). It won't work for tricky situations containing certain characters such as smileys (for more info on this potential problem, see https://dzone.com/articles/the-right-way-to-reverse-a-string-in-java).
This question already has answers here:
Java program to find the character that appears the most number of times in a String?
(8 answers)
Closed 6 years ago.
I got a task from my university today:
Write a program that reads a ( short ) text from the user and prints the so called max letter (most common character in string) , that the letter which the greatest number of occurrences of the given text .
Here it is enough to look at English letters (A- Z) , and not differentiate between uppercase and lowercase letters in the count of the number of occurrences .
For example, if : text = " Ada bada " so should the print show the most common character, this example it would be a.
This is an introductory course, so in this submission we do not need to use the " scanner - class" . We have not gone through this so much.
The program will use the show message input two get the text from user .
Info: The program shall not use while loop ( true / false ) , "return " statement / "break " statement .
I've been struggling with how I can get char values into a table.. am I correct I need to use array to search for most common character? I think I need to use the binarySearch, but that only supports int not char.
I'll be happy for any answers. hint's and solutions. etc.. if you're very kind a full working program, but again please don't use the things I have written down in the "info" section above.
My code:
String text = showInputDialog("Write a short text: ");
//format string to char
String a = text;
char c = a.charAt(4);
/*with this layout it collects number 4 character in the text and print out.
* I could as always go with many char c... but that wouldn't be a clean program * code.. I think I need to make it into a for-loop.. I have only worked with * *for-loops with numbers, not char (letters).. Help? :)
*/
out.print( text + "\n" + c)
//each letter into 1 char, into table
//search for most used letter
Here's the common logic:
split your string into chars
loop over the chars
store the occurrences in a hash, putting the letter as key and occurrences as value
return the highest value in the hash
As how to split string into chars, etc., you can use Google. :)
Here's a similar question.
There's a common program asked to write in schools to calculate the frequency of a letter in a given String. The only thing you gotta do here is find which letter has the maximum frequency. Here's a code that illustrates it:
String s <--- value entered by user
char max_alpha=' '; int max_freq=0, ct=0;
char c;
for(int i=0;i<s.length();i++){
c=s.charAt(i);
if((c>='a'&&c<='z')||(c>='A'&&c<='Z')){
for(int j=0;j<s.length();j++){
if(s.charAt(j)==c)
ct++;
} //for j
}
if(ct>max_freq){
max_freq=ct;
max_alpha=c;
}
ct=0;
s=s.replace(c,'*');
}
System.out.println("Letter appearing maximum times is "+max_alpha);
System.out.println(max_alpha+" appears "+max_freq+" times");
NOTE: This program presumes that all characters in the string are in the same case, i.e., uppercase or lowercase. You can convert the string to a particular case just after getting the input.
I guess this is not a good assigment, if you are unsure about how to start. I wish you for having better teachers!
So you have a text, as:
String text = showInputDialog("Write a short text: ");
The next thing is to have a loop which goes trough each letter of this text, and gets each char of it:
for (int i=0;i<text.length();i++) {
char c=text.charAt(i);
}
Then comes the calculation. The easiest thing is to use a hashMap. I am unsure if this is a good topic for a beginners course, so I guess a more beginner friendly solution would be a better fit.
Make an array of integers - this is the "table" you are referring to.
Each item in the array will correspond to the occurrance of one letter, e.g. histogram[0] will count how many "A", histogram[1] will count how many "B" you have found.
int[] histogram = new int[26]; // assume English alphabet only
for (int i=0;i<histogram.length;i++) {
histogram[i]=0;
}
for (int i=0;i<text.length();i++) {
char c=Character.toUppercase(text.charAt(i));
if ((c>=65) && (c<=90)) {
// it is a letter, histogram[0] contains occurrences of "A", etc.
histogram[c-65]=histogram[c-65]+1;
}
}
Then finally find the biggest occurrence with a for loop...
int candidate=0;
int max=0;
for (int i=0;i<histogram.length;i++) {
if (histogram[i]>max) {
// this has higher occurrence than our previous candidate
max=histogram[i];
candidate=i; // this is the index of char, i.e. 0 if A has the max occurrence
}
}
And print the result:
System.out.println(Character.toString((char)(candidate+65));
Note how messy this all comes as we use ASCII codes, and only letters... Not to mention that this solution does not work at all for non-English texts.
If you have the power of generics and hashmaps, and know some more string functions, this mess can be simplified as:
String text = showInputDialog("Write a short text: ");
Map<Char,Integer> histogram=new HashMap<Char,Integer>();
for (int i=0;i<text.length();i++) {
char c=text.toUppercase().charAt(i));
if (histogram.containsKey(c)) {
// we know this letter, increment its occurrence
int occurrence=histogram.get(c);
histogram.put(c,occurrence+1);
}
else {
// we dunno this letter yet, it is the first occurrence
histogram.put(c,1);
}
}
char candidate=' ';
int max=0;
for (Char c:histogram.keySet()) {
if (histogram.get(c)>max) {
// this has higher occurrence than our previous candidate
max=histogram.get(c);
candidate=c; // this is the char itself
}
}
System.out.println(c);
small print: i didn't run this code but it shall be ok.
first of all I want to say that I am kinda new to Java. So please be easy on me :)
I made this code, but I cannot find a way to change a character at a certain substring in my progress bar. What I want to do is this:
My progressbar is made out of 62 characters (including |). I want the 50th character to be changed into the letter B (uppercase).It should look something like this: |#########----B--|
I tried several things, but I dont know where to put the line of code to make this work. I tried using the substring and the replace code, but I can't find a way to make this work. Maybe I need to write my code in a different way to make this work? I hope someone can help me.
Thanks in advance!
int ecttotal = ectcourse1+ectcourse2+ectcourse3+ectcourse4+ectcourse5+ectcourse6+ectcourse7;
int ectmax = 60;
int ectavg = ectmax - ecttotal;
//Progressbar
int MAX_ROWS = 1;
for (int row = 1; row == MAX_ROWS; row++)
{
System.out.print("|");
for (int hash = 1; hash <= ecttotal; hash++)
System.out.print ("#");
for (int hyphen = 1; hyphen <= ectavg; hyphen++)
System.out.print ("-");
System.out.print("|");
}
System.out.println("");
System.out.println("");
}
Can you tell a little more what you want. Because what i sea it that, that you write some string into console. And is not way to change that what you already print to console.
Substring you can use only at String varibles.
If you want to change lettir with substring method in string varible try smth. like this:
String a="thi is long string try it";
if(a.length()>50){
a=a.substring(0,49)+"B"+a.substring(51);
}
Other way to change charater in string is to use string builder like this:
StringBuilder a= new StringBuilder("thi is long string try it");
a.setCharAt(50, 'B');
Sure you must first check the length of string to avoid the exceptions.
I hope that I helped you :)
Java StringBuilder has method setCharAt which can replace character at position with new character.
StringBuilder myName = new StringBuilder(<original string>);
myName.setCharAt(<position>, <character to replace>);
<position> starts with index 0
In your case:
StringBuilder myName = new StringBuilder("big longgggg string");
myName.setCharAt(50, 'B');
You can replace a certain index in a string by concatenating a new string around the intended index. For example the following code replaces the letter c with the letter X. Where 2 is the intended index to replace.
In other words, this code replaces the 3rd character in the string.
String s = "abcde";
s = s.substring(0, 2) + "X" + s.substring(3);
System.out.println(s);
This is a program that lets user input 6 random letters, and the program sorts these letters in order. Ex user inputs j, d, e, l, w, q and program outputs d, e, j, l, q, w.
Unfortunately the code freaks out and does not sort a thing. Note: I am using a GUI
Under public I created a class and an array to eventually house all inputted letters
class Abc {
String letter;
Abc (String _letter) {
letter = _letter;
}
}
ArrayList <Abc> alphabet = new ArrayList <Abc>(3); //note its 3, not 6 like in the example
After user types in a letter in a textField, they press the "addButton" which adds and saves the value in the array.
String letter = letterField.getText();
//Store values in array
Abc a = new Abc(letter);
alphabet.add(a);
Now for the actual 'sorting' part. Which takes place after user presses a "Play" button.
String[] abc = new String[3]; //LINE I FORGOT TO ADD
for (int k = 0; k < abc.length; k++) {
abc[k] = letterField.getText();
int x;
for (int i = 0; i < abc.length; i++) {
// Asume first value is x
x = i;
for (int j = i + 1; j < abc.length; j++) {
//find smallest value in array (random)
if (abc[j].compareToIgnoreCase(abc[x]) < 0) {
x = j;
}
}
if (x != i) {
//swap the values if not in correct order
final String temp = abc[i];
abc[i] = abc[x];
abc[x] = temp;
}
textArea.append(abc[i] + "\n");// Output correct order
}
}
I had originally used this code to sort integers, the only difference between that program and this program is the int/String and this one I am currently working on allows the user to input the letters and the program does not randomize them like it did with the integer program.
I had thought this would be enough code to do the trick and organize some letters, but apparently not.
For the actually problem, when I input the letters and add them to the array and press "play" the program freaks and a lovely error pops up...
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "d"
Note: 'd' being the last letter I inputted for the last time I tested the program...all of five seconds ago.
Any hints or advice would be greatly appreciated!
A NumberFormatException is thrown when you attempt to parse some text into a number, but the text is not a number, such as in your example: "d".
You mentioned that you had this code working with integers, then converted it to work with letters. Most likely, you forgot to take out the code (which you haven't shown here) that parses the input into a number. You should take out that code and accept the user's input as text as originally inputted.
You are probably using parseInt() or something similar in the part of the code, where you get input from user. That method should be off now, as you no longer want to change input from String to any number.
By the way, just for information, class Arrays in java include some sorting methods. You can check those at this site