Why isn't this code working?
What I'm trying to do is create a ReplaceAll() method but it is giving ArrayIndexOutOfBoundsException error.
This is Class file:
public class MyString{
private char[] data;
public MyString(){
}
public MyString(String s){
data = s.toCharArray();
}
public char replaceFirst(char o, char n){
for(int i=0; i<data.length; i++){
if(data[i]==o){
data[i]=n;
}
}
return data[n];
}
and this is my tester file:
public class Tester{
public static void main(String[] args){
MyString m1 = new MyString();
MyString m2 = new MyString("Nafees");
System.out.println(m2.replaceFirst('N','k'));
}
}
Thanks in advance.
And if I made any mistake while asking this question, sorry.
Problem is in the last line of the method:
return data[n];
n is the replacement character, but java interprets it as a number here. The n is a character "k", which is also number 107. And your input string "Nafees" doesn't have so many characters.
If you want to get the String with replaced characters, you should use this instead:
return new String(data);
P.S. You should rename the method or change implementation, because you are replacing all matching characters, not first.
You return at the end of the method data[n]. However n is the parameter (a char) of your method and not an integer. So He will convert n as an integer which will be out of the limit of your array of character.
Whilst it's great that everyone is helping diagnose and debug your code, I'd like to point out that replaceFirst is part of the standard Java String object since Java 1.4, although it does expect a regex and string instead of two char values.
https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replaceFirst(java.lang.String,%20java.lang.String)
There is also a replaceAll method on String, if that was the intended behaviour.
Related
I'm writing a code that would replace the lettering in a string with another letter. However, my current assignment wants the code in a particular format. I attempted the code below:
public String replaceLetter(String word, char letterToReplace, char replacingLetter)
{
letterToReplace = Character.toString(letterToReplace);
replacingLetter = Character.toString(replacingLetter);
word = word.replaceAll(letterToReplace, replacingLetter);
return word;
}
Please excuse any inefficiencies in the coding as I am still relatively new to programming in general. I also recently got into chars and strings more intensely,so there is much I do not know in terms of some of the rules or traits pertaining to them. Are the errors in my code illogical? The IDE I am currently using is an online one that has the sole purpose of collecting my assignment for grading. Whenever I compile the code above, it gives me errors such as a missing return statement, so I would not count it as reliable. The IDE itself is extremely limited, and cannot compile things such as switch statements, so I'd prefer if I could keep it as simple as possible. However, I have found that the IDE will recognize most correct coding. I did try to attempt the coding with a for statement:
public String replaceLetter(String word, char letterToReplace, char replacingLetter)
{
for (int i = 0; i < word.length(); i++)
{
char ca = word.charAt(i);
if (ca == letterToReplace)
{
word = (word.substring(0,i)+ replacingLetter + word.substring(i+1));
}
}
return word;
}
But I also ran into errors. Any help in correcting my syntax would be appreciated.
You're trying to assign your Strings created with Character.toString to your existing chars, then you're passing those chars into the replaceAll function (which doesn't accept chars, it needs Strings). Try changing your code to this:
public String replaceLetter(String word, char letterToReplace, char replacingLetter)
{
String letterToReplaceAsString = Character.toString(letterToReplace);
String replacingLetterAsString = Character.toString(replacingLetter);
word = word.replaceAll(letterToReplaceAsString, replacingLetterAsString);
return word;
}
Edit: As ajb pointed out, you could also call replace (instead of replaceAll) passing in your original char perimeters, and skip the step of assigning your Strings. Note that replace will still replace all occurrences of the char:
return word.replace(letterToReplace, replacingLetter);
Your letterToReplace and replacingLetter variables are character type and you are assigning String to them as Character.toString method returns string.
Change the variable type to String and you will be good to go.
I'm doing something like
public static String[] list = {"a","b","c","d",} //It gives me a NullPointeException if I didn't use static
public String encrypt(String a){
a = a.replace(list[0],list[2]);
a = a.replace(list[4],list[3]);
return a;
}
and I have another method that just reverses it
public String decrypt(String a){
a = a.replace(list[2],list[0]);
a = a.replace(list[3],list[4]);
return a;
}
Of course this is simplified, the real code I'm using uses the entire alphabet and some numbers. So here's my problem: If I input something like 123 into encrypt() and it outputs ngV then I input ngV into decrypt() it gives me like 1q3. Only some of the letters are correctly switched and some aren't. Is there something with the replace() method using array values that I'm missing? I'm obviously new to Java.
Also I read Java replace() problems but replaceAll() didn't work out.
I suspect your question is "why is chaining .replace acting oddly" and the array is not changing. You can prove that replace does not change the array quite easily:
System.out.println(Arrays.toString(list));
encrypt("abc");
System.out.println(Arrays.toString(list));
So what is going on with your code? Each time you replace a letter you end up with a new string, that again you replace letters on. I don't have your full source code so I'll show with a real simple version:
a = a.replace("a", "b");
a = a.replace("b", "c");
a = a.replace("c", "d");
For "abc" is.... 'ddd'.
The answer to this is to look at each letter at a time and change it. Loop through the string and create a new one.
Here is my code:
package test;
public class Stringtest {
public static void main(String[] args) {
String a = " love y ou !! ";
String b = a.trim();
b.replaceAll("\\s+","");
System.out.println(b);
}
}
But the result is still:"love y ou !!". It just remove the white space at the start and the end of the string. Did I do anything wrong?
Strings are immutable which means you can't change them. That is why replaceAll doesn't affect original string, but creates new one with replaced values which you need to store somewhere, possibly even in original reference.
So try with
b = b.replaceAll("\\s+", "");
replaceAll method of String will return back string after removing all the spaces and as String is immutable, so assign the outcome of replaceAll back to b like:
b = b.replaceAll("\\s+","");//Note you dont need to trim if you want to replace every spaces.
Run the following and you'll understand what you have done.
System.out.println(b.replaceAll("\\s+",""));
string.replace() returns the replaced string
you forgot to store the substring which return from replaceAll method.
try
b = b.replaceAll("\\s+","");
I hope the evening finds you well. My problem tonight is that I'm trying to create a char array, but I can't use any of the good ways to do it. I can only use String.length and String.charAt() my code is a miserable sad mess. This kind of combines all the things I've ever been terrible at so far.
Ultimately what I'll be trying to do is find a way to insert, delete, and replace things given certain indexes of a user-input string, but one step at a time, right?
This is what I have right now for my insert method, it's not even close to done obviously. All I'm really trying to figure out here, is how to print out my array, because when I try to print it out right now its just printing blanks. I apologize for my ineptitude.
public String insert_text(String fromtest){
System.out.println(fromtest.length());
System.out.println(fromtest);
for(int i=0;i<fromtest.length();i++){
text=new char[fromtest.charAt(i)];
System.out.println(text[i]);
}
System.out.println("* Enter the starting position:");
int startpos=k.nextInt();
System.out.println("* Enter the text you want to insert:");
String instring=k.next();
return fromtest;
}
I'm not sure why, but the prompt just say that the only things we can use are Sting.Length and String.charAt and store them to an array which I forgot to mentioned should be private char [] text.
String.toCharArray() is the function that you are looking for. It converts the String into equivalent Char array.
Convert an input String to char[] as the following sample code:
public static void main(String args[])
{
String str = "Sameer";
char[] cArray = str.toCharArray();
//Now perform functions with your charArray
}
Hope this helps.
Why can't you use
char [] input = fromtest.toCharArray(); // get's the character array as called...
if you can't use toCharArray you could try
char [] array = new char[fromtest.length()];
for (int i = 0; i < fromtest.length(); i++) {
array[i] = fromtest.charAt(i);
}
You can print each char by :
System.out.println(fromtest.charAt(i));
public String insert_text(String fromtest){
Char[] charArray = fromtest.toCharArray();
// do whateveryou want;
return fromtest;
}
So far i understand your problem is you need to make dynamic array of what String is passed in this function,
use char[] charArray = string.toCharArray();
but what you are doing i prefer you stack and queues
I wrote a text, and i want to change some chars to any other chars which the user will choosing them, I tried and couldn't find the correct answer, so please guide me.
the code in the MyTest Class is:
public String replace(String input,char from,char to){
String input2 ="";
String input3="";
this.input=input3;
for(int i=0;i<input.length();i++){
for(int j=0;j<input3.length();j++){
if(input.charAt(i)==input3.charAt(j)){
input2=input3.replace(from, to);
System.out.println(input2);
}
}
}
return input2;
}
And the code in the Main Class:
System.out.println("please enter the new character: ");
char c1 = scan.next().charAt(0);
System.out.println("Please choose the letters that you want to change it which in the text:");
String ltr = scan.next();
obj1.convertChars(ltr, c1);
(1) What you should do:
There is a simple method for what you are after: String#replace(char,char):
String replaced = myString.replace(from,to);
(2) Why your code fails:
Note you are iterating and trying to invoke replace() on input3, while it is an empty string! you never changed it! effectively your method do nothing (except assigning the instance variable input. Definetly not what you wanted.
(3) Also important: Strings in java are immutable
In java, String is immutable - so what you are doing is actually crating a new string with replaced characters, and NOT replacing the characters in the same string object!
Changing the String is not as simple, and should be avoided, but can be done using the reflection API.
What you want to do shouldn't even be a method. Here's why:
public String replace(String input,char from,char to){
return input.replace(from, to);
}
Thus kind of method adds no value - you should just call the replace() method of String directly.
The question seemed a bit unclear. I hope you want a function like this:
Call this function from the main function. Pass the string "abcde", 'a', 'x'. It will return you "xbcde".
public String replace(String inputStr, char from, char to){
StringBuffer newString=new StringBuffer();
for(int i=0;i<inputStr.length();i++){
if(inputStr.charAt(i)==from){
newString.append(to);
}
else{
newString.append(inputStr.charAt(i));
}
}
return newString.toString();
}