Java .replace() seems to modify an array [duplicate] - java

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.

Related

java method that returns patterned string from range

I'm brand new to Java. I've been assigned a test and I'm stuck on how to complete it. So the case is like so -
Create a method that returns a patterned string from range A000 to ZZZZ. Parameter for the method is string itself, so if we pass A000 it should return A001, if we pass A001 it should return A002 and so on... A009... A999... AA00... AA99... AB00... AB01... AB99... AC00... to AZZZ.
I've been able to increment the numbers, but am unable to change them to letters when they reach 99. Let's say I input AZ99; it should return AZA0, but I don't know how I should write that logic.
I thought of using arrays, but then I'd have to save each iteration of the pattern in the array, and that seems unfeasible. Then I thought I'd use if...else and write the instances where the numbers should increment into letters, but that's unnecessarily long too. I know this can be done by proper logic, but it fails me. I've scrounged multiple threads on stackoverflow, but I can't find one quite like this one.
This is what I've got so far -
public class StringSeries {
public static String returnString (String inputString) {
String newString = inputString.substring(0,2);
String completeNewString = newString +
(Integer.parseInt(inputString.substring(1,inputString.length()))+1);
System.out.println(completeNewString);
return completeNewString;
}
public static void main (String[] args){
Scanner sc = new Scanner();
String inputString = sc.nextLine();
returnString(inputString);
sc.close();
}
}
I need suggestions on how to do this. Also, please elaborate on how a certain logic would work.
Thanks!
P.S. I've looked a lot for this type of question on forums, and haven't been able to find any. I also realize that this question may be repetitive for non-newbies. I request that you don't be rude and point out similar threads if you know where they are. Thanks.
This is much easier than it seems. All you need to do is convert the string to a number in base 36 (Integer.valueOf, Integer.parseUnsignedInt), add one to it, and convert it to an upper case base-36 string (Integer.toString plus converting that to upper case).

Problem with creating a replaceFirst() method in Java

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.

char Array difficulties

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

Java: Writing a static function that takes a string as an argument and returns the third word in the string?

Write a static function that takes a string as an argument and returns
the third word in the string. Call the function with the following
string:
This is my string
Print the result to the console.
New to java and having a hard time figuring this problem at (new at java). Im not sure how to approach the problem. Ive figured out how to get the results with an array but is an array even a possible answer? What im having trouble with most is the returning of the 3rd word of the string.
edit:
Heres what I have currently to figure what was asked for, just not sure if its correct
public class problem4 {
public static void main(String[] args) {
String[] str;
str = strArray();
System.out.println(str[2]);
}
public static String[] strArray(){
String[] array = {"This", "is", "my", "string"};
return array;
}
}
This is on the right track, but its not exactly what the problem is asking for.
You are missing two big things here. First, you need to put this into a static function that takes a string (meaning you have to make your own, you cant use main). That would look something like this -
public static String getThirdWord(String s){
Second, your logic works assuming you get a String array. The problem though states you are getting a String. That means you have to do some work before you can use your (mostly correct) array notation. Here is what you need
String[] words = s.split(" ");
This will take the input, and 'split' it into parts around the spaces. You are essentially getting back an array of the individual words.
Then you can start using the array notation -
return words[2];
HOWEVER: you might get an input that is less than three words! This would cause an exception to be thrown when you do words[2]. Your problem does not state what to do in such a case, but you will almost certinally need to check the size by doing if(words.size>2)

How do I print content of reference in JAVA?

Newbie question comming up. Trying to get my head around JAVA.
How do I print out the content of the reference and not just their postition ? My program is ment to get some text in from the user, and print it out in a reverse order.
Here is my program (so far):
package myProgram;
import javax.swing.JOptionPane;
public class someRandomClass {
public static void main(String[] args) {
String word = JOptionPane.showInputDialog("Write som text here");
StringBuilder outPut = new StringBuilder();
for (int i = word.length()-1; i>=0; i--){
outPut.append(i);
}
System.out.println(outPut.toString());
}
}
I am greatfull for any help and tips! :)
In the line
outPut.append(i);
you are appending the value of your loop counter. You surely mean
outPut.append(word.charAt(i));
You seem to appending the integers instead of the appropriate characters. Try this instead:
outPut.append(word.substring(i, i + 1))
This way, the individual characters of word are appended to your StringBuilder. Note that the append method could also take a char as an argument, so you are also able to use word.charAt(i).
So, you want to emit the character at the position? Try using String.charAt.
outPut.append(word.charAt(i));
I'd probably avoid that and just index the char[] from String.toCharArray, though.
To be honest, I'd avoid doing the reversal loop manually to begin with... try something as follows:
final String word = JOptionPane.showInputDialog("Enter text below");
System.out.println(new StringBuilder(word).reverse());
StringBuilder.reverse should do the work for you (likely in a more efficient way, too). You also don't need to call toString manually, as println will do that for you.

Categories