I have the following snippet for a hangman game I'm developing in Eclipse:
String secret = "apple";
String str = "-----"
for (int i = 0; i < 5; i++) {
if (letter == secret.charAt(i)){
str = str.replace(str.charAt(i), letter);
}
}
System.out.println(str);
Unfortunately, this is printing out
aaaaa
instead of
a----
How would I get this working?
The JavaDoc of String#replace(char, char) states that it will replace all occurrences not just the first.
Since you want to make a hangman game, you need to only replace the positions where letter appears in secret
It might be better to manually replace the characters in a String using a StringBuilder or a char[]
char[] secret="apple".toCharArray();
char[] str= new char[secret.length];
Arrays.fill(str, '-');
for (int i = 0; i < secret.length; i++) {
if (letter ==secret[i]){
str[i] = letter;
}
}
System.out.println(new String(str));
If you want really set only a character in a String, you could do something like this:
StringBuilder sbStr = new StringBuilder(str);
sbStr.setCharAt(4, 'x');
This is your code refactored:
String secret = "apple";
String str = "-----"
StringBuilder sbStr = new StringBuilder(str);
for (int i = 0; i < 5; i++) {
if (letter == secret.charAt(i)){
sbStr.setCharAt(i, letter);
}
}
System.out.println(sbStr.toString());
str.replace(str.charAt(i), letter); will not work because it does not replace a single character, but all charachters in the String matching str.charAt(i), what you could do is use StringBuilders to change the character at a given index, like this:
String secret = "apple";
StringBuilder str = new StringBuilder("-----");
for (int i = 0; i < 5; i++) {
if (letter == secret.charAt(i)){
str.setCharAt(i, letter);
}
}
System.out.println(str.toString()); // Or simply: System.out.println(str);
If you don't want to use StringBuilder, something like this will also work:
String secret = "apple";
String str = "-----";
for (int i = 0; i < 5; i++) {
if (letter == secret.charAt(i)){
str = str.substring(0, i) + secret.charAt(i) + str.substring(i);
}
}
System.out.println(str);
Although I advice a StringBuilder in this case.
Hope this helps.
I suggest to use String builder for both secret and str, and mark guess character in secret too, because your solution may fails for repeating characters
char letter = 'a';
StringBuilder secret = new StringBuilder("apple");
StringBuilder str = new StringBuilder("-----");
int index = secret.indexOf(String.valueOf(letter));
if(index != -1)
{
secret.setCharAt(index, '-');
str.setCharAt(index, letter);
}
System.out.println(secret);
System.out.println(str);
Hopes that Helps
Related
This is what I got. It works for now, but if I type, for example, "I like bananas", I get 'pIp ppipkpep pbpapnpapnpaps', while I'm aiming to get 'pI pLpipkpe pbpapnpapnpaps.
Every solution I tried came down to using an 'if statement', trying to check if the character at said position in the original 'encText'is equal to ' ', and if so, making it equal to ' ' as well in the newText array before checking if the position required an 'p' or the char from the original array.. However, everytime I tried that, I'd get an array out of bounds exception.
static void pEncrypt() {
System.out.println("Adding P");
Scanner in = new Scanner(System.in);
String encText = in.nextLine();
int k = encText.length();
char[] charsEncText = encText.toCharArray();
char[] newText = new char[2*k];
int j = 1;
for (int i = 0; i < (k*2); i++) {
if (i%2 == 0) {
newText[i] = 'p';
} else {
newText[i] = charsEncText[i-j];
j++;
}
}
System.out.println(newText);
}
A simpler solution is to use replaceAll with a positive lookahead.
String str = "I like bananas";
String res = str.replaceAll("(?=[^ ])", "p");
System.out.println(res); // "pI plpipkpe pbpapnpapnpaps"
Demo
You can try this way.
static void pEncrypt() {
System.out.println("Adding P");
Scanner in = new Scanner(System.in);
String encText = in.nextLine();
int k = encText.length();
char[] charsEncText = encText.toCharArray();
char[] newText = new char[2*k];
int j=0;
for(int i=0;i<k;i++)
{
if(charsEncText[i]==' ')
{
newText[j]=charsEncText[i];
j++;
}
else{
newText[j]='p';
newText[j+1]=charsEncText[i];
j=j+2;
}
}
System.out.println(newText);
}
Assuming one does not need a char[], I would just concatenate to a String. Something like:
public static String pEncrypt(String org)
{
String ret = "";
for (int i = 0; i < org.length(); ++i) {
char ch = org.charAt(i);
if (ch != ' ') {
ret += "p" + ch;
}
else {
ret += ' ';
}
}
return ret;
}
Also, to make things a bit easier, it is generally a good idea to separate the I/O (i.e., the Scanner and the println) from the processing. That way, one can write test cases rather than attempting to keep inputting the information.
Sample Output:
helloworld ==> phpeplplpopwpoprplpd
I like bananas ==> pI plpipkpe pbpapnpapnpaps
Java keeps giving me a compiler error, telling me the charAt method should be a variable and I can't figure out why?
Here's my code:
String s = "12345";
for (int i=0;i<s.length(); i++){
s.charAt(i)= s.charAt((i+1)%s.length());
System.out.println(s);
}
}
s.charAt(i)= s.charAt((i+1)%s.length());
You can't do this in Java. Strings are immutable, and s.charAt(i) evaluates to value, not a variable. This is why it's telling you it should be a variable
Lets say you are doing a rotation cipher.
String s = "12345";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i+1);
ch += 1;
if (ch > '5')
ch -= 5;
sb.append(ch);
}
System.out.println(sb);
String is immutable but StringBuilder is mutable and you can use it to create a new String. Note: the character 1 is the ASCII value of that character or 49. https://en.wikipedia.org/wiki/ASCII so your maths has to take this into account.
If you just want to rotate the characters, you can do
String s2 = s.substring(1) + s.charAt(0);
A Java String is immutable, but there is StringBuilder (which is a mutable sequence of characters). You could do something like,
String str = "12345";
StringBuilder sb = new StringBuilder(str);
for (int i = 0; i < sb.length(); i++) {
sb.setCharAt(i, str.charAt((i + 1) % sb.length()));
}
System.out.println(sb);
I get
23451
s.charAt(i)= s.charAt((i+1)%s.length());, you charAt() returns a character at a particular index , you can't assign to it.
The result of charAt() is a char that cannot be assigned. Moreover, Strings in Java are immutable, meaning that there is no mechanism for changing a string after it has been constructed.
Use StringBuilder to make a new string from the old one character-by-character:
String s = "12345";
StringBuilder res = new StringBuilder("12345");
for (int i=0 ; i<s.length() ; i++) {
res.setCharAt(i, s.charAt((i+1)%s.length()));
}
System.out.println(res);
Or probably you could use an array of char.
char[] s = "12345".toCharArray();
for (int i = 0; i < s.length; i++) {
s[i] = s[(i + 1) % s.length];
System.out.println(s);
}
If given a string like "go to med!" how do I replace just the even characters for example? The problem is that while my code takes care of the first word, the space between the words counts as a character itself and messes up replacements in the second word with the first letter of the second word becoming classified as even.
Here is my attempt
public static void main(String[] args) {
String s = "go to med!";
String alphabetS = "abcdefghijklmnopqrstuvwxyz";
StringBuilder sb = new StringBuilder(s);
for(int i=0; i<s.length(); i++){
char currChar = s.charAt(i);
int idx = alphabetS.indexOf(currChar);
if (idx != -1)
if (i%2==1)
{
sb.setCharAt(i, '*');
}
}
System.out.println(sb);
}
This gives output "g+ +o m+d!"
(second letter being correctly replaced by + for being even, but the first letter of the second word should not be replaced as "first" is not "even".
How to make the index to ignore white spaces?
Preferably the answer should not contain arrays, only Char and String methods.
You could simply split the input on the space and process each work individually. You could then use a StringJoiner to piece together the result, for example...
String s = "go to med!!";
String alphabetS = "abcdefghijklmnopqrstuvwxyz";
String[] words = s.split(" ");
StringJoiner sj = new StringJoiner(" ");
for (String word : words) {
StringBuilder sb = new StringBuilder(word);
for (int i = 0; i < sb.length(); i++) {
char currChar = sb.charAt(i);
int idx = alphabetS.indexOf(currChar);
if (idx != -1) {
if (i % 2 == 1) {
sb.setCharAt(i, '*');
}
}
}
sj.add(sb.toString());
}
System.out.println(sj.toString());
which outputs
g* t* m*d!!
could this be done without using arrays - just with char and string methods?
Instead of relying on i, you need a separate counter, which tracks which point your up to and which can be used to ignore invalid characters, for example
String s = "go to med!!";
String alphabetS = "abcdefghijklmnopqrstuvwxyz";
StringBuilder sb = new StringBuilder(s);
int counter = 0;
for (int i = 0; i < sb.length(); i++) {
char currChar = sb.charAt(i);
int idx = alphabetS.indexOf(currChar);
if (idx != -1) {
if (counter % 2 == 1) {
System.out.println("!!");
sb.setCharAt(i, '*');
}
counter++;
}
}
System.out.println(sb.toString());
which still outputs
g* t* m*d!!
this gives: g* t* m*d*
public static void main(String[] args) {
String s = "go to med!";
int realindex=0;
StringBuilder sb = new StringBuilder();
for(int i=0; i<s.length(); i++){
char currChar = s.charAt(i);
if ((currChar != ' '))
{
if (realindex%2==1) {
currChar = '*';
}
realindex++;
}
sb.append(currChar);
}
System.out.println(sb.toString());
}
There are a thousand different ways to accomplish your goal, but assuming you want to keep using your solution, here is what you could do
public static void main(String[] args) {
String s = "go to med!! goodbye cruel world";
String alphabetS = "abcdefghijklmnopqrstuvwxyz";
StringBuilder sb = new StringBuilder(s);
for (int i = 0,relativePosition=0; i < s.length(); i++,relativePosition++) {
char currChar = s.charAt(i);
if(currChar == ' '){relativePosition=-1;continue;}
int idx = alphabetS.indexOf(currChar);
if (idx != -1)
if (relativePosition % 2 == 1)
sb.setCharAt(i, '*');
}
System.out.println(sb);
}
that prints
g* t* m*d!! g*o*b*e c*u*l w*r*d
What about introducing flag about even state of letter?
boolean isEven=false;
for(int i=0; i<s.length(); i++){
char currChar = s.charAt(i);
int idx = alphabetS.indexOf(currChar);
if (idx != -1)
if(isEven){
isEven=false;
sb.setCharAt(i, '*');
}else {
isEven = true;
}
}
}
I'm trying to write a code that will give this output:
plusOut("12xy34", "xy") → "++xy++"
it returns a string where the characters in the original have been replaced by + except for where the 2nd string appears in the first string, but im having problems with my code. Here it is:
public String plusOut(String str, String word) {
String newString = "";
for (int i=0; i<str.length()-1; i++) {
if (str.substring(i, word.length()).equals(word)) {
newString = newString + str.substring(i, word.length());
}
else {
newString = newString + "+";
}
}
return newString;
}
There are some bugs in your code, see the comments.
public String plusOut(String str, String word) {
String newString = "";
// iterate up to length() to catch the last char if word.length() is 1
for (int i = 0; i < str.length(); i++) {
// use min() to avoid an IndexOutOfRange
String sub = str.substring(i, Math.min(i+word.length(), str.length()));
if (sub.equals(word)) {
newString = newString + sub;
// skip remaining characters of word
i += sub.length()-1;
}
else {
newString = newString + "+";
}
}
return newString;
}
In addition to that, I'd use a StringBuilder instead of the + operator.
You should really tell us what specific problems you are facing with your current code. In any case, here's how I would do it:
Split str on all occurrences of word to form a String[].
Loop through this array and append a number of '+' characters to newString corresponding to the length of whatever element of the array you're on.
On the same loop iteration, append word to newString, unless of course you're on the last element of the array.
This is what I mean:
public static String plusOut(String str, String word) {
StringBuilder newString = new StringBuilder(str.length());
String[] split = str.split(word);
for (int i = 0; i < split.length; i++) {
for (int j = 0; j < split[i].length(); j++)
newString.append('+');
if (i != split.length - 1)
newString.append(word);
}
return newString.toString();
}
Oh and just another tip: try to avoid appending to strings repeatedly within a loop. If you need to, use a StringBuilder instead.
System.out.println(plusOut("12xy34", "xy"));
++xy++
The best and simplest way I can think of is to use regular expressions and do a replaceAll.
General idea will be to get the second character build an regex with that and replaceAll with the regular expression and the replacement character.
public String plusOut(String str, String word) {
String regEx="[^"+Pattern.quote(word)+"]";
str.replaceAll(regEx,"+");
}
Note that the Pattern.quote() will make sure that your word won't screw the regex.
I didn't try out the code, but it should work without a problem.
This will do that for you.
public String plusOut(String str, String word) {
if(!str.contains(word)){
System.out.println("Word not found in string!");
return "Ut-oh!";
}
int indexOfStart = str.indexOf(word);
StringBuilder sb = new StringBuilder();
for(int i = 0; i<indexOfStart; i++){
sb.append('+');
}
sb.append(word);
for(int i=indexOfStart+word.length(); i < str.length(); i++){
sb.append('+');
}
return sb.toString();
}
So many answers! Well, here's mine as well:
public static String plusOut(String str, String word) {
String output = "";
int index = str.indexOf(word); // if -1 is returned, replace all chars
for (int i= 0; i < str.length(); i++) {
if(i == index)
{
output += word;
i += word.length() -1; // because i++ will still occurr
continue;
}
output += "+";
}
return output;
}
and test code in main:
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String test = "somethinghello12345.1!#";
System.out.println(test + " -> " + plusOut(test, "hello"));
test = "somethinghello12345.1!#";
System.out.println(test + " -> " + plusOut(test, "not gonna work"));
}
will produce the ouput:
somethinghello12345.1!# -> +++++++++hello+++++++++
somethinghello12345.1!# -> +++++++++++++++++++++++
Try this :
public static String plusOut(String word, String find) {
StringBuilder newStr = new StringBuilder();
int start = word.indexOf(find);
if (start > -1) {
for (int i = 0; i < start; i++) {
newStr.append("+");
}
newStr.append(find);
for (int i = 0; i < word.length() - (start + find.length()); i++) {
newStr.append("+");
}
}
return newStr;
}
I am attempting to split the components of a string into an array, so that they can be accessed more easily.
For example: 4+5= should become ['4','+','5','='].
Edit: -
I would need consecutive numbers to be joined together, and whitespaces can be ignored. Thanks again!
You can solve it with regex lookaround mechanism.
String str = "10 * 10 - 40 + 100/2 = 110";
//but first lets remove white spaces (it will makes regex easier)
String strWithoutSpaces=str.replaceAll("\\s+", "");
String[] tokens = strWithoutSpaces.split("(?<=[-+*/=])|(?=[-+*/=])");
for (String t:tokens)
System.out.print(t+",");
Output:
10,*,10,-,40,+,100,/,2,=,110,
You can use
String str = "4+5=";
String[] tokens = str.split("(?!^)");
for (String s : tokens) {
System.out.println(s);
}
This will output
4
+
5
=
You could use toCharArray() method
String s ="4+5=";
char [] stArr = s.toCharArray();
for(char ss: stArr){
System.out.println(ss);
}
Out put
4
+
5
=
You could do something like this:
public static void main(String args[]) {
String str = "45+5-26";
String strArr[] = new String[str.length()];
StringBuffer sb = new StringBuffer();
int cnt = 0;
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch != '\0') {
if (ch == ' ') {
continue;
}
if (ch >= 48 && ch <= 57) {
sb.append(ch);
continue;
} else {
strArr[cnt++] = sb.toString();
sb = new StringBuffer();
// sb.append(ch);
}
strArr[cnt++] = ch + "";
sb = new StringBuffer();
}
}
strArr[cnt++] = sb.toString();
sb = new StringBuffer();
System.out.println("strArray: ");
for (int i = 0; i < strArr.length; i++) {
if (strArr[i] == null)
break;
System.out.println(strArr[i]);
}
}
If you have only operators as the separator between the numbers this would be more easy to get the string tokens.
You can modify as below if you want the tokens separated by a comma:
for (int i = 0; i < strArr.length; i++) {
if (strArr[i] == null)
break;
// System.out.println(strArr[i]);
if(i!=0)
sbResult.append(",");
sbResult.append(strArr[i]);
}
System.out.println("sbResult: "+sbResult.toString());