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;
}
Related
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 1 year ago.
Improve this question
We will be given a string s. Suppose for example "creepfe". What we want to do is to remove duplicate and instead add a new letter in that place and new letter must be distinct letter available next to the duplicate letter in alphabetical order. So it goes like this :
creepfe to crefpfe -- first e is distinct and second e is changed to f which is distinct upto that.
crefpfe to crefpge -- second f is changed to g since we already have f before.
crefpge to crefpgf -- since e is already present.
Now again we got f duplicate , so change it to crefpgg , which again got g duplicate so finally we reach "crefpgh" which has all distinct letters.
Started learning java recently and a working code is appreciated ,BUT a good algorithm is what really needed.
Edit : yes capitals do count as duplicates as well. And string length is limited to 10-15 so no worry about running out of distinct letter.
Here's a solution. I m using recursion to left shift the letters if there are duplicates. I also went back and redid my code to include sets as mentioned by MBo. Its not the most efficient, but its a start while you wait for advice from more experienced members of SO
public class tester {
public static void main(String[] args){
//Application.launch(testclass.class, args);
String str = "creepFeZZ";
System.out.println(processStr(str));
}
public static String processStr(String str){
StringBuilder sb = new StringBuilder();
HashSet<String> seen = new HashSet<>();
insertStr(sb, seen, String.valueOf(str.charAt(0)));
for (int i=1; i<str.length(); i++){
char currentchar = str.charAt(i);
char processedchar = goNext(seen, currentchar);
insertStr(sb, seen, String.valueOf(processedchar));
}
//System.out.println(seen.toString());
return sb.toString();
}
private static void insertStr(StringBuilder sb, HashSet seen, String str){
seen.add(str.toLowerCase());
sb.append(str);
}
private static char goNext(HashSet seen, char c){
if (c>= 65 && c<=90){
//if uppercase letter, check if contains lowercase version
if (seen.contains(String.valueOf((char)(c+32)))){
c = goNext(seen, (char)(c+1));
}
//any left shifting will overflow back to A
return (char) ((c -(int) 'A') % 26 +(int) 'A');
}else{
//if lowercase letter, just check if contains
if (seen.contains(String.valueOf((char)(c)))){
c = goNext(seen, (char)(c+1));
}
//any left shifting will overflow back to a
return (char)((c-(int) 'a') % 26 +(int) 'a');
}
}
}
This gives output of:
crefpGhZA
Find the position where the string contains a duplicate. There are various methods to this. You can Google to find the most efficient one that fits your approach.
Generate the next character in alphabetical order. The following code shows how this can be done
String value = "C";
int charValue = value.charAt(0);
String next = String.valueOf( (char) (charValue + 1));
System.out.println(next);
Repeat the process until there are no more duplicates (have a while loop which breaks when there are no more duplicates)
I am writing a hangman program and one of the requirements to a hangman game is preventing the user from entering the same letter twice.
I have written the code for that, but the problem is every time I enter a letter it says it is already entered. I need to only say it when it is entered the second time. You guys have any suggestions? I've been trying to fix this for the past few hours, I figured I could ask on here to find some help. I already looked at another Stackoverflow question regarding something similar to this but all those solutions have the same result.
In Java, how can I determine if a char array contains a particular character?
I've tried something like this but it won't work either:
boolean contains = false;
for (char c : store) {
if (c == character) {
System.out.println("Already Entered");
contains = true;
break;
}
}
if (contains) {
// loop to top
continue;
}
SECOND CLASS-
public void hangman(String word, int life) {
KeyboardReader reader = new KeyboardReader();
char[] letter = new char[word.length()];
char[] store = new char[word.length()];
String guess;
int i = 0, tries = 0, incorrect = 0, count = 1, v = 0;
while (i < word.length()) {
letter[i] = '-';
I would just use the String.contains() method:
String aString = "abc";
char aChar = 'a';
return aString.contains(aChar + "");
To keep track of guessed letters you can use a StringBuffer, appending them using a StringBuffer.append() to append new letters (maintaining state) and use the StringBuffer.toString() method to get the String representation when you need to do the comparison above.
Since Java 1.5 the class String contains the method contains(). My idea is to collect all entered letters into a string variable and using above method:
// My code line
String letterAlreadyEntered = "";
// Your code line
char character = reader.readLine().charAt(0);
// My code line
if (letterAlreadyEntered.contains("" + character) == true) {
//Put code here what ever you want to do with existing letter
} else {
letterAlreadyEntered += character;
}
In my opinion, this is an easier way to check for occurrences than in arrays, where you have to write your own check method.
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 7 years ago.
Improve this question
I showed this to my teacher and he said that I was 99% correct. The only problem is that I did not put an argument in the first class. I'm so confused because I don't think I've learned that part yet : (
Class 1:
import java.util.*;
public class hearts {
public static void hearts1(String[] args) {
char heart = '♥';
for (int i = 0; 1 < 254; i++)
{
System.out.print(heart++ + " ");
}
}
}
Class 2:
public class Caller {
public static void main(String[] args){
hearts.hearts1(args);
}
}
Generally I would advise you to not use "magical appeared" numbers in this sort of situation.
Furthermore you have created an endless loop because your loop condition is (1<254) which is alway true because 1 will always be smaller than 254.
Therefore I would write
for (char currentChar = heart; currentChar < '❣'; currentChar++)
{
System.out.print(currentChar + " ");
}
instead of
for (int i = 0; 1 < 254; i++)
{
System.out.print(heart++ + " ");
}
And generally said you are not using any arguments in your code...You are passing some arguments but you're never actually using them.
Maybe you should change your first class like this:
public static void hearts1(char startChar) {
char heart = startChar;
//...
}
And then change the calling to this:
hearts.hearts1('♥');
If you use this approach I would advise you to check if the given char-parameter (in Class1) is within a certain range of characters so you don't end up processing some chars you newver wanted to...
To take the idea with the scanner into consideration you could simply
public static hearts1() {
Scanner scanner = new Scanner(System.in);
System.outprinln("Enter starting char:");
String userInput = scanner.next();
char heart = userInput.charAt(0);
for (char currentChar = heart; currentChar < '❣'; currentChar++) {
System.out.print(currentChar + " ");
}
scanner.close();
}
But I don't advise this method because dependingon the user input it takes quite long for the program to print out the chars and furthermore it's really hard for the user to give the heart symbol as an input.
I hope this answers your question (partly)
Greetings Raven
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
I have to be able to input any two words as a string. Invoke a method that takes that string and returns the first word. Lastly display that word.
The method has to be a for loop method. I kind of know how to use substring, and I know how to return the first word by just using .substring(0,x) x being how long the first word is.
How can I make it so that no matter what phrase I use for the string, it will always return the first word? And please explain what you do, because this is my first year in a CS class. Thank you!
I have to be able to input any two words as a string
The zero, one, infinity design rule says there is no such thing as two. Lets design it to work with any number of words.
String words = "One two many lots"; // This will be our input
and then invoke and display the first word returned from the method,
So we need a method that takes a String and returns a String.
// Method that returns the first word
public static String firstWord(String input) {
return input.split(" ")[0]; // Create array of words and return the 0th word
}
static lets us call it from main without needing to create instances of anything. public lets us call it from another class if we want.
.split(" ") creates an array of Strings delimited at every space.
[0] indexes into that array and gives the first word since arrays in java are zero indexed (they start counting at 0).
and the method has to be a for loop method
Ah crap, then we have to do it the hard way.
// Method that returns the first word
public static String firstWord(String input) {
String result = ""; // Return empty string if no space found
for(int i = 0; i < input.length(); i++)
{
if(input.charAt(i) == ' ')
{
result = input.substring(0, i);
break; // because we're done
}
}
return result;
}
I kind of know how to use substring, and I know how to return the first word by just using .substring(0,x) x being how long the first word is.
There it is, using those methods you mentioned and the for loop. What more could you want?
But how can I make it so that no matter what phrase I use for the string, it will always return the first word?
Man you're picky :) OK fine:
// Method that returns the first word
public static String firstWord(String input) {
String result = input; // if no space found later, input is the first word
for(int i = 0; i < input.length(); i++)
{
if(input.charAt(i) == ' ')
{
result = input.substring(0, i);
break;
}
}
return result;
}
Put it all together it looks like this:
public class FirstWord {
public static void main(String[] args) throws Exception
{
String words = "One two many lots"; // This will be our input
System.out.println(firstWord(words));
}
// Method that returns the first word
public static String firstWord(String input) {
for(int i = 0; i < input.length(); i++)
{
if(input.charAt(i) == ' ')
{
return input.substring(0, i);
}
}
return input;
}
}
And it prints this:
One
Hey wait, you changed the firstWord method there.
Yeah I did. This style avoids the need for a result string. Multiple returns are frowned on by old programmers that never got used to garbage collected languages or using finally. They want one place to clean up their resources but this is java so we don't care. Which style you should use depends on your instructor.
And please explain what you do, because this is my first year in a CS class. Thank you!
What do I do? I post awesome! :)
Hope it helps.
String line = "Hello my name is...";
int spaceIndex = line.indexOf(" ");
String firstWord = line.subString(0, spaceIndex);
So, you can think of line as an array of chars. Therefore, line.indexOf(" ") gets the index of the space in the line variable. Then, the substring part uses that information to get all of the characters leading up to spaceIndex. So, if space index is 5, it will the substring method will return the indexes of 0,1,2,3,4. This is therefore going to return your first word.
The first word is probably the substring that comes before the first space. So write:
int x = input.indexOf(" ");
But what if there is no space? x will be equal to -1, so you'll need to adjust it to the very end of the input:
if (x==-1) { x = input.length(); }
Then use that in your substring method, just as you were planning. Now you just have to handle the case where input is the blank string "", since there is no first word in that case.
Since you did not specify the order and what you consider as a word, I'll assume that you want to check in given sentence, until the first space.
Simply do
int indexOfSpace = sentence.indexOf(" ");
firstWord = indexOfSpace == -1 ? sentence : sentence.substring(0, indexOfSpace);
Note that this will give an IndexOutOfBoundException if there is no space in the sentence.
An alternative would be
String sentences[] = sentence.split(" ");
String firstWord = sentence[0];
Of if you really need a loop,
String firstWord = sentence;
for(int i = 0; i < sentence.length(); i++)
{
if(sentence.charAt(i) == ' ')
{
sentence = firstWord.substring(0, i);
break;
}
}
You may get the position of the 'space' character in the input string using String.indexOf(String str) which returns the index of the first occurrence of the string in passed to the method.
E.g.:
int spaceIndex = input.indexOf(" ");
String firstWord = input.substring(0, spaceIndex);
Maybe this can help you figure out the solution to your problem. Most users on this site don't like doing homework for students, before you ask a question, make sure to go over your ISC book examples. They're really helpful.
String Str = new String("Welcome to Stackoverflow");
System.out.print("Return Value :" );
System.out.println(Str.substring(5) );
System.out.print("Return Value :" );
System.out.println(Str.substring(5, 10) );