Reverse and repeat String words in java [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
So I am having trouble repeating my text 3 times, reversing the sentence and counting the letters's in the word. Can someone please help me out? I have tried googling and looking for a method and cannot seem to get any of them to work. It would be greatly appreciated

You have a misplaced semi-colon at the end of your if-statement meaning that the statement after it will always be executed.
if(text.charAt(i) == 'e'); // Remove the last character here
{
System.out.println("e :" + text.charAt(i) + i);
count++;
}
As for your reverseLetters function, I don't know if the return text; outside of your for loop can be reached but you're overwriting the value of reverse on each iteration. I think what you should be trying instead is to append the value of text.charAt(j) to the value of reverse like so:
String reverse = ""; // Must be initialised to an empty string
for(int j = text.length()-1; j >= 0; j--)
{
reverse += text.charAt(j);
/* The rest of the contents of your loop here */
And what do you expect your repeatLetters function to do? You're assigning the given String to a local variable named repeat and then you're just returning that value without doing anything. You could use a loop to append text to an empty String three times and return that.
String repeat = "";
for (int i = 0; i < 3; i++)
{
repeat += text + " ";
}
return repeat;

Related

Rephrasing a paragraph using java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Very new java student here (My first post, sorry for wrong formatting). I need help with rephrasing a paragraph.
I need to change the letters of the paragraph to the 13th next letter ie changing a to n and so on meanwhile conserving the structure of the paragraph ie line breaks, full stops, etc...I have only been able to change a word so far and need to expand this code to be able to do it with a paragraph...Thanks in advance...Much appreciated...
public class Assignment1b {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Please type any word: ");
String word = s.nextLine();
String ROT13 = "";
for(int i = 0; i < word.length(); i++){
char c = word.charAt(i);
int value = c - 'a' + 1;
value = value + 13;
char ency = (char)((value % 26) + 'a' - 1);
ROT13 = ROT13 + ency;
}
System.out.println("The encrypted word is: " + ROT13);
}
}
General good programming practice: one method does one thing, and one thing only. This makes code easier to read, test, maintain and reuse. I suggest you start by taking the stuff in your for () loop and sticking it in a new method. Call it private char encryptCharacter(char oldCharacter), or some such. Add the return value to your ROT13 string to build the answer, as you are currently doing.
Your problem is now in this secondary module - how to preserve line breaks, spaces and similar characters. Refer to Charlie Armstrong's comment, that will help you identify them. You will probably end up with something like:
private char encryptCharacter(char oldCharacter) {
if (isWhiteSpaceOrPunctuation(oldCharacter)) {
return oldCharacter;
} else {
// add your code to encrypt the character here
return encryptedCharacter;
}
}
private boolean isWhiteSpaceOrPunctuation(char character) {
// return true or false, as appropriate
}
First you need to split paragraph by words, using method split of String class and passing the char, that splits words, in this case, the space " ". This method return array of String (String[]), which means, array of words, but I convert it to List<String> using Arrays.asList() method, to facilitate the process. Next, I iterate this list, and apply the rephrase method, that encript or change each word.
// this split your paragraph, and invoke your code, which means, rephrase method by word
public static String encript(String paragraph){
// split words by spaces, but punctuation still
List<String> words = Arrays.asList(paragraph.split(" ").clone());
StringBuilder sb = new StringBuilder();
for(String word : words) {
// rephrase and append
sb.append(rephrase(word));
}
return sb.toString();
}
// this is your code in a method, I recommend you rebuild this method using StringBuilder, it is more efficient
public static String rephrase(String word){
String ROT13 = "";
for(int i = 0; i < word.length(); i++){
char c = word.charAt(i);
int value = c - 'a' + 1;
value = value + 13;
char ency = (char)((value % 26) + 'a' - 1);
ROT13 = ROT13 + ency;
}
return ROT13;
}

How should I print out the position of the first occurrence of a specific letter in a String? [duplicate]

This question already has answers here:
Java: method to get position of a match in a String?
(14 answers)
Closed 2 years ago.
Say my string is as follows
String str = "What is up tod?";
I want to use an accessor method to print out the position of the first occurrence of the letter "t". What is an efficient use of code to use? I also want to ensure that it doesn't try to tell me the occurrence of the second "t". Please keep in mind I am searching for how to do this in Java.
Any help or link to similar question is greatly appreciated.
Unless I'm missing something, use String.indexOf(int) like
String str = "What is up tod?";
System.out.println(str.indexOf('t'));
Which outputs the first match
3
Alternatively, iterate the characters of the String from left to right checking for 't'; if you find it, print the index and terminate the loop. Like,
String str = "What is up tod?";
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == 't') {
System.out.println(i);
break;
}
}

Coding Challenge in Java: Given Letters and Returning What Rank They are in [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Hey so for practice I found this coding challenge which I have now been working on for a few days. I have the first part, but I just can't seem to figure out how to continue from where I am. Here is the challenge:
Consider a "word" as any sequence of capital letters A-Z (not limited to
just "dictionary words"). For any word with at least two different letters,
there are other words composed of the same letters but in a different order (for
instance, STATIONARILY/ANTIROYALIST, which happen to both be dictionary words;
for our purposes "AAIILNORSTTY" is also a "word" composed of the same letters as
these two).
We can then assign a number to every word, based on where it falls in an
alphabetically sorted list of all words made up of the same set of letters. One
way to do this would be to generate the entire list of words and find the
desired one, but this would be slow if the word is long.
Write a program which takes a word as a command line argument and prints to
standard output its number. Do not use the method above of generating the entire
list. Your program should be able to accept any word 20 letters or less in
length (possibly with some letters repeated), and should use no more than 1 GB
of memory and take no more than 500 milliseconds to run. Any answer we check
will fit in a 64-bit integer.
Sample words, with their rank:
ABAB = 2
AAAB = 1
BAAA = 4
QUESTION = 24572
BOOKKEEPER = 10743
NONINTUITIVENESS = 8222334634
Your program will be judged on how fast it runs and how clearly the code is
written. We will be running your program as well as reading the source code, so
anything you can do to make this process easier would be appreciated.
So far, the code I have can return the correct answer if all of the letters are different. Here is my code:
import java.util.Arrays;
import java.util.Scanner;
public class AthenaDility {
public static void main (String[] args) {
//Finds word that is entered
Scanner scan = new Scanner (System.in);
String word = scan.next();
scan.close();
//added value
int value = 1;
//alphabetical representation
char[] charm = word.toCharArray();
char[] alphaCharm = word.toCharArray();
Arrays.sort(alphaCharm);
//Comparer
for (int m = 0; m < word.length(); m++) {
for (int c = 0; c < word.length()-1; c++) {
System.out.println(charm[m] + " " + alphaCharm[c]);
//Skips if alphaCharm is a space
if (alphaCharm[c] == '-') {
}
//If the same letter it breaks look and begins next
else if (charm[m] == alphaCharm[c]) {
System.out.println("Deleting: " + alphaCharm[c]);
alphaCharm[c] = '-'; //Delete letter for it is used and cannot be used to compare at later points
break;
}
//if the letter in alphaCharm comes before charm
else if (charm[m] > alphaCharm[c]){
System.out.println("Found!");
//factorial calculation
int factorial = 1;
//takes the length of the word minus the current location and one after for factorial
for (int f = word.length() - m - 1; f > 0; f--) {
System.out.print(f + " ");
factorial *= f;
}
//end loop
//Adding to others
System.out.println("\n" + "Factorial: " + factorial);
value += factorial;
}
else {
}
}
}
//Result
System.out.println("end: " + value);
}
}
To try and explain it as simply as I can, it creates two strings: one is the letters in alphabetical order and one is the original word. The program then compares each letter at a time and any letter that comes before the one in the original word alphabetically causes a factorial calculation for the number of combinations that would exist before the first word.
The part I need help factoring in is if the strings entered have more than one of the same letter. I have literally spent DAYS trying to figure this out. Thank you in advance!
p.s. the code has a lot of System.out.println for testing sake

valid word counter out of bounds error [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
{
public static int WordCount (String cString)
{
String currentWord;
int index;
int spacePos;
int validWordCount=0;
boolean validWord;
char upClowC;
cString=cString.trim()+" ";
spacePos=cString.indexOf(" ");
validWord=true;
for(index=0;index<cString.length();index++)
{
currentWord=cString.substring(0,spacePos);
upClowC=Character.toUpperCase(currentWord.charAt(index));
if(upClowC<'A'||upClowC>'Z')
{
validWord=false;
}
}
if(validWord==true)
{
validWordCount++;
}
return validWordCount;
}
public static void main(String[] args)
{
String sentence;
System.out.println("enter a sentence:");
sentence=EasyIn.getString();
WordCount(sentence);
}
}
I'm trying to create a method which takes a sentence and picks out the valid words (i.e. no numbers or symbols), but I keep getting an out of bounds error.
I can't use an array.
Your problem is here:
currentWord = cString.substring(0, spacePos);
upClowC = Character.toUpperCase(currentWord.charAt(index));
currentWord gets shorter, but index is still running from 0 to the length of the string.
General notes:
Follow Java naming conventions and change the name of your method to begin with small letter
if(validWord) is enough when you want to compare something to true, otherwise it's like asking "is it true that the value is true" instead of simply "is the value true"
Next time post your stack trace to get better and sooner help
In your code, you are doing
spacePos = cString.indexOf(" ");
And then inside the loop:
currentWord = cString.substring(0,spacePos);
upClowC = Character.toUpperCase(currentWord.charAt(index));
Now, because of the loop, the index will take values from 0 to your string length minus 1. If your substring (currentWord) is smaller than your string - which probably is -, then currentWord.charAt(index) will try to index out of the bounds of the substring, which is why you get the error.

Find all substring contain a keyword [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I want to find all the substring of one String that contains a key word.
Ex: "This is the keyword in the string".
Output: the keyword, this is the keyword, the keyword in the string, is the keyword in ....
I am think of finding all the substrings first then try to filter one by one. But I think that would be very bad solution.
Could you please give me some advice to do that!. Thank you very much.
I have edited to just find the sequence of tokens.
Try this:
String str = "abcdefkeybncv...";
String key = "key";
int index = str.indexOf(key);
ArrayList<String> sub = new ArrayList<String>();
for (int i = 0; i < str.length(); i++) {
for (int j = 0; j <= str.length() - i; j++) {
String s = str.substring(i, i+j);
if(s.indexOf(key) >= 0){
sub.add(s);
}
}
}
System.out.println(sub);
Output for the code above:
[abcdefkey, abcdefkeyb, abcdefkeybn, abcdefkeybnc, abcdefkeybncv, abcdefkeybncv., abcdefkeybncv.., abcdefkeybncv..., bcdefkey, bcdefkeyb, bcdefkeybn, bcdefkeybnc, bcdefkeybncv, bcdefkeybncv., bcdefkeybncv.., bcdefkeybncv..., cdefkey, cdefkeyb, cdefkeybn, cdefkeybnc, cdefkeybncv, cdefkeybncv., cdefkeybncv.., cdefkeybncv..., defkey, defkeyb, defkeybn, defkeybnc, defkeybncv, defkeybncv., defkeybncv.., defkeybncv..., efkey, efkeyb, efkeybn, efkeybnc, efkeybncv, efkeybncv., efkeybncv.., efkeybncv..., fkey, fkeyb, fkeybn, fkeybnc, fkeybncv, fkeybncv., fkeybncv.., fkeybncv..., key, keyb, keybn, keybnc, keybncv, keybncv., keybncv.., keybncv...]
Build suffix array: http://en.wikipedia.org/wiki/Suffix_array
Use binary search to find your substring there
Move up and down from this point in suffix array while suffixes starts with substring

Categories

Resources