Output don't recognize alphabets - java

Okay so this my code where i try to print characters
however I do not understand why my output don't recognize the alphabetical char while printing in output. NOTE: I given input of length as 4 here.

You need to fix the calculation of alphabet. For given input length as 4 the calculated value for number and alphabet is 2 and your second for-loop is created as for(int i = 2; i < 2; i++). The loop body will not be executed.

Related

How to divide a string into equal groups of n characters padded with blank spaces in Java?

How to create a method that will take imput of a String and an integer n and output the String divided into parts consisting of n characters and separated by a blank space? For example, imput String: "THISISFUN", integer:3, result: "THI SIS FUN".
When you answer, can you please really try to explain what each part of the code does? I really want to understand it.
I tried using StringBuilder and the split() method but the problem is that I don't understand how all of that works. Therefore, I ended up kind of thoughtlessly pasting parts of codes from different online articles which doesn't work the best if you want to actually learn something, especially if you simply cannot find any posts about a specific issue. I could only find things like: "how to divide the String into n parts" and "how to ad a space after a specific char" which are sort of similar issues but not the same.
Here is one way to do it:
public static void splitString(String str, int groupSize){
char[] arr = str.toCharArray(); // Split the string into character array ①
// Iterate over array and print the characters
for(int i=0; i<arr.length; i++){
// If 'i' is a multiple of 'groupSize' ②
if(i > 0 && i % groupSize == 0){ ③
System.out.print(" ");
}
System.out.print(arr[i]);
}
}
① Split the string into a character array (so that you can access the characters individually). You can also do it using the charAt() method without splitting the string into an array. Read the Javadoc for more details.
② Check if the loop counter i is a multiple of groupSize
③ Note the use of System.out.print() as we do not want to print a newline. Here you can use a StringBuilder too and print the contents at the end instead of printing the characters inside the loop.

I keep getting a "java.lang.StringIndexOutOfBoundsException" even though my for loop counter adjusts for length by subtracting 1

So my main goal is to create a program that can decrypt a caesar cipher. I have everything set up so that I have the regular alphabet set up in one array and then a decoder array where I have shifted the alphabet based on a shift/key the user inputs. (ie. if the user inputs a shift of 6, the regular alphabet array starts a, b, c... and then the decoder array starts g, h, i...).
I am currently stuck on going through the encrypted message (user inputted) and decoding each letter one by one by matching it up to the decoder array. It keeps giving me an index out of bounds error even though in the for loop that I have set up, I have subtracted one from the length of the message to compensate for it starting at 0.
The error only happens at the last character too (that's what the 35 is. I have a 35 character string that I'm using to test). But when I try to print the decoded message up until the error, I'm just getting nulls (I'm storing each decoded char in an array and print each character stored as the for loop is running).
Here is the piece of code that I'm currently stuck on:
//Decoding message by looping through each letter in String message
for (int x = 0; x < (message.length() - 1); x ++) //Gets next letter in message
{
for (int y = 0; y < (decodedArray.length - 1); x++) //Goes through decodedArray array
{
if (String.valueOf(message.charAt(x)) == (decodedArray[y])) //Comparing character to each position in decodedArray
{
decodedMessage[x] = alphabetArray[y];
}
System.out.print(decodedMessage[x]); //Testing only. Prints each character stored in array but only printing nulls.
}
}
I haven't added any checks for spaces yet because I'm currently stuck on this error but if any of you can add that, that would be greatly appreciated. I'm not sure if comparing a char to a space would work.
According to the current code in the question, I can say there are 2 problems with your code,
If you need to compare char, you can directly use to == operator without needing it to convert it to string by using String.ValueOf().
You are incrementing x in the 2nd loop, instead you need to increment y

How can user input a sequence of numbers into array// Java

so i've been trying to do this one thing which is letting user input his sequence number into array. I mean f.e. if he wanted to input 9901229976 and 9 would be Array[0], another 9 would be array[1], 0 would be array [2] and so on and so on, i've tried many things and didin't come up with the answer, i'm totally stuck with that, if the answer is so obvious i'm really, but i need answer as it is my project:(
This is how you would do it:
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
int[] array = new int[input.length()];
for(int i = 0; i < input.length(); i++){
array[i] = Integer.parseInt(Character.toString(input.charAt(i)));
}
String.charAt(int position) gets the Character located at a
certain position in the String.
Character.toString(Characters ch)
converts a Character to a String.
Integer.parseInt(String s) converts a String to an Integer.
So, what the code does is it goes through each character in the string, converts that character to a String, and then uses the Integer.parseInt() method in order to get that original character as a number.
array is now an array of the digits of the number that the user inputted. This should answer your question.

Find the letter that occur most times from user with using tables [duplicate]

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.

String replace isn't working in for loop - Java

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

Categories