I have a two dimensional array that contains pairs of strings. If one string is found it should replace it with its pair.
The code:
for (int i = 0; i < pairs.length; i++) {
if (name.contains(pairs[i][0])) {
name.replaceAll(pairs[i][0], abbr[i][1]);
}
}
It is not replacing the strings. What is the error?
You are neglecting to assign the result of replaceAll, and so the modification is lost.
Perhaps you want to keep the modified string as name:
for (int i = 0; i < pairs.length; i++) {
if (name.contains(pairs[i][0])) {
name = name.replaceAll(pairs[i][0], abbr[i][1]);
}
}
Note that java String objects are immutable, so calling name.replaceAll doesn't modify name, it returns a new String with the modifications.
String is immutable.
name.replaceAll(pairs[i][0], abbr[i][1]);
creates a new String (it doesn't modify the "name" String)
Try
name = name.replaceAll(pairs[i][0], abbr[i][1]);
A modified version of the string is being created, however it's return value is being lost.
name = name.replaceAll(pairs[i][0], abbr[i][1]);
should work.
Related
I have below string output :
["Kolkata","data can be, null",null,"05/31/2020",null]
but I want to have the output like below format in Java
["Kolkata","data can be, null","","05/31/2020",""]
please help me .
I am converting object to json data . Please see the below codes
List<String> test = new ArrayList<>();
List<Object[]> data =query.list();
for (int i = 0; i < data.size(); i++) {
Object[] row = (Object[]) data.get(i);
String jsonString = gson.toJson(row);
test.add(jsonString);
}
I want to apply this on jsonString variable using java 7 as not using java 8
Gson doesn't allow you to change the serialized form of strings.
Probably better to change your objects -> replace null by empty string before serialization.
You can replace every null value with an empty string inside the array using another for loop. Here is an example that will do the same.
Object[] row = new Object[]{"Kolkata","data can be, null",null,"05/31/2020",null};
for (int i = 0; i < row.length; i++) {
if (row[i] == null) {
row[i] = "";
}
}
Hello everyone i am trying to remove an name that the user has put in from an String Array, i am new to programming and i have tried this but it doesn't work. Can someone help me or tell me what i am doing wrong?
String [] myName = {"Testname","Charel","melissa","Kelly"};
removeName(myName);
public void removeName(String[] names )
{
Scanner sc = new Scanner(System.in);
String name = "";
name = sc.nextLine();
for (int i = 0; i < names.length; i++) {
name = names[i-1];
}
}
How can i do this?
You probably need to use Lists for this. Your list will be a list of String, and use remove() method to do this.
An array's length is fixed and can't be changed this way.
Useful Link : Removing items from a list
First off, an array does not change size after it is initialized, the only way to change the size of an array is to replace it with a new array! So in order to not end up with a double entry or an empty field, you would need to make a new array that is one size shorter, and write the names you want to keep into that.
An array might be ill-suited for your purposes, so consider using a list or an ArrayList. A list can be resized, so removing an element will automatically shorten the list. I recommend you look into that.
Lastly, you currently aren't even comparing your input to your fields. Replace name = names[i-1]; with something along the lines of
if(name.equals(names[i]))
//TODO: Remove from list
See here for more details about String.equals()!
Also, keep in mind that the user input might not match any name at all, so prepare for that case as well!
To remove an element from an array in Java, you need to create a new array and copy over all the elements you want to keep. That is because Java arrays are fixed-size.
For example, to remove an element at a particular index, you could do it like this:
public static String[] remove(String[] array, int index) {
String[] result = new String[array.length - 1];
System.arraycopy(array, 0, result, 0, index);
System.arraycopy(array, index + 1, result, index, result.length - index);
return result;
}
You would then remove melissa from your array as follows:
String[] names = { "Testname", "Charel", "Melissa", "Kelly" };
names = remove(names, 2);
System.out.println(Arrays.toString(names));
Output
[Testname, Charel, Kelly]
Of course, it would be much easier to do it using a List:
List<String> names = new ArrayList<>(Arrays.asList("Testname", "Charel", "Melissa", "Kelly"));
names.remove(2);
System.out.println(names);
Or:
List<String> names = new ArrayList<>(Arrays.asList("Testname", "Charel", "Melissa", "Kelly"));
names.remove("Melissa");
System.out.println(names);
Output of both is the same as above.
There are some simple methods using java api provide by jdk, for example:
String [] myName = {"Testname","Charel","melissa","Kelly"};
List<String> container = new ArrayList(Arrays.asList(myName));
container.remove("Charel");
String[] result = new String[myName.length - 1];
container.toArray(result);
Alternatively you can also use this to convert array to list,
Collections.addAll(container, myName);
String [] myName = {"Testname","Charel","melissa","Kelly"};
removeName(myName);
public void removeName(String[] names )
{
Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
for (int i = 0; i < names.length; i++) {
if(names[i]==name)
{
for(int j=i;j<names.length-1;j++)
{
names[j]=names[j+1];
}
}
}
}
I am trying to convert String builder to String array in java.I have used to String method to convert the Stringbuilder to String and then use split method to convert it to String array.
I am facing some issue in array size. The output of String builder is as follows: 0,,1,,,,,,,,,,2,,,. Actually it contains 15 elements, but it's showing the size of stringbuilder as 18. And after converting to String array, it's showing size as 13.
Am I doing wrong method? Is there is other method to convert String builder to String Array?
StringBuilder output = new StringBuilder();
for (String str : listToSearch) {
int index = findIndex(headerArrayList, str);
if (index > -1) {
output.append(index);
} else {
output.append(str);
}
output.append(",");
}
String out = output.toString();
String[] destIndexArray = out.split(",");
The findIndex method:
private static int findIndex(List<String> headerList, String element) {
for (int i = 0; i < headerList.size(); i++) {
if (headerList.get(i).equals(element)) {
return i;
}
}
return -1;
}
Am I doing wrong method?
There are many places your code need improvements. I'm suggesting some:
Instead of re-inventing wheel, look for existing API: https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#indexOf(java.lang.Object)
You can add only Strings instead of index.
for (String str :listToSearch) {
int index=headerArrayList.indexOf(str);
if (index < 0) {
output.append(str);
output.append(",");
}
// if(!headerArrayList.contains(str))
// output.append(str);
// output.append(",");
}
Use List<String> instead of StringBuilder.
Is there is other method to convert String builder to String Array?
Yes, but if you follow above points, you won't need it. but since you asked. See this: How can a StringBuilder best be converted to a String[]?
See using stringbuilder and again manipulating it and converting it into array is not a good idea. Instead insert everything into list of string, and to check if string is integer or not use this :
str.matches("^-?\\d+$");
And if you want to convert it into array you can do that
String[] str = list.toArray(new String[list.size()])
Have you simply tried in it with one line code:
stringBuilder.toString().split("delimiter"); ?
Which is in your case, might look like:
destIndexArray = output.toString().split(",");
If that doesnt work, then instead of converting into a StringBuilder, you can do this:
List<String> output = new List<String>();
for (String str : listToSearch) {
int index = findIndex(headerArrayList, str);
if (index > -1) {
output.add(index);
} else {
output.add(str);
}
}
I think in this case you can do whatever with your list, no need of delimiter. Hope it helps!
I have to add a String parameter to the end of an array. And throw an exception if the String already exists in the array. I don't know. Can anyone help?
This is what I have so far
public static void addCity (String city) throws Exception
{
for (int i = 0; i < MAX_CITIES;i++)
{
if (city == cityNames[i])
throw new Exception("This city already exists");
}
String [] temp = new String[cityNames.length+1];
for (int i = 0; i < cityNames.length;i++) {
temp[i] = cityNames[i];
}
temp[temp.length-1] = city;
cityNames = temp;
manyItems++;
}
To test if String a equals String b, use a.equals(b), not a == b.
(a == b works in C++, not Java.)
Your code looks fine except for the String comparison:
if (city == cityNames[i])
This won't do a proper String comparison: it will only compare the object references, which will usually be false.
Use String.equals for this:
if (city.equals(cityNames[i]))
It'd be easier to use a List:
List<String> cityNames = new ArrayList<String>();
if(cityNames.contains(city)) {
throw new Exception("This city already exists");
}
cityNames.add(city);
What is MAX_CITIES? I think your first loop should be until i < cityNames.length, not MAX_CITIES, since you don't seem to be updating MAX_CITIES when you increase the size of the array.
You should be using the equals() method to compare String objects, rather than ==.
It also might be nice if instead of just making the new array one element bigger, you double the size. That way you don't have to go through all the work of copying the array every time you add a new element. You'd need a variable to keep track of the next empty spot in the array, and it would look something like this:
if (nextEmptyIndex == cityNames.length)
{
String [] temp = new String[cityNames.length*2];
for (int i = 0; i < cityNames.length;i++) {
temp[i] = cityNames[i];
}
}
temp[nextEmptyIndex] = city;
nextEmptyIndex++;
manyItems++;
I want to know if is it possible to Store a String variable on a String array?
I cant explain it well but here is what i do:
String st1 = "",st2 = "",st3 = "",st4 = "";
String[] str = {st1,st2,st3,st4};
Unfortunately when i use for loop the str gets the value of st1 and st2 and st3 ans st4 not the variable it self..
This is what i want to do exactly on my mind..
Whenever a have a String array for example:
String[] containsValue = { "hi", "hello", "there" };
String strHi, strHello, strThere;
String[] getContainsValue = { strHi, strHello, strThere };
for (int x = 0; x < getContainsValue.length; x++) {
getContainsValue[x] = containsValue[x];
}
The value of:
strHi = "hi"
strHello = "hello"
strThere = "there";
Basically i want to transfer that value of containsValue[] to 3 String which is strHi, strHello, strThere that are stored in getContainsValue[]. Then use for loop to asign value to them came from containsValue[].
Is this posible? If so then can you give me some format how to do it? thanks..
You can use Map<K,V>.
Map<String,String> map=new HashMap<String,String>();
map.put("strHi","hi");
map.put("strHello","hello");
map.put("strThere","there");
System.out.println(map.get("strHello"));
You can use enum class as the Array needed :
public enum EnumModifE {
str1("1"), str2("2"), str3("3");
String value;
EnumModifE(final String s) {
this.value = s;
}
public void setValue(final String s) {
this.value = s;
}
}
public class EnumModifM {
public static void main(final String[] args) {
for (final EnumModifE eme : EnumModifE.values()) {
System.out.println(eme + "\t" + eme.value);
}
EnumModifE.str1.setValue("Hello");
EnumModifE.str2.setValue("all");
EnumModifE.str3.setValue("[wo]men");
for (final EnumModifE eme : EnumModifE.values()) {
System.out.println(eme + "\t" + eme.value);
}
}
}
Output
str1 1
str2 2
str3 3
str1 Hello
str2 all
str3 [wo]men
See in Effective Java use of enum
The concept you are looking for is an "l-value". Briefly, when you are using a variable, are you using the value contained in the variable, or are you talking about the variable itself so that you can store something else into it? You want array that you're calling getContainsValue to have l-values for strHi, strHello, and strThere. Unfortunately there is no way to do this in Java. Initializing getContainsValue with strHi, strHello, and strThere uses the values of those variables, not their l-values.
Let's step back a bit and talk more about l-values vs values (sometimes, r-values). Consider the following code snippet:
int i = 17;
i = i + 1;
That second line is obviously not an equation; that would be nonsensical. Instead, it is an assignment. The meaning of i on the left and right sides of an assignment is different. On the right hand side, i means to use the value of that variable, in this case 17. On the left hand side, i means the variable itself, as a destination for storing values. Even though they look the same, the use of i on the right-hand side is for its value (more specifically, its r-value) and the use of i on the left-hand side is for its l-value.
In Java, there is no way to express the l-value of a variable in an array initializer, so what you're trying to do doesn't work. As others have pointed out, in other languages like C this is possible, by using the & (address-of) operator.
Since Java has limited ways of expressing l-values, usually the concept of "a place to store something into" is expressed via a reference to an object. One can then use this reference to store into fields of that object or to call methods on that object.
Suppose we have a class like this:
class MyContainer {
String str;
void setString(String s) { str = s; }
String getString() { return str; }
}
We could then rewrite your code to do something like the following:
String[] containsValue = { "hi", "hello", "there" };
MyContainer hiCont = new MyContainer();
MyContainer helloCont = new MyContainer();
MyContainer thereCont = new MyContainer();
MyContainer[] getContainsValue = { hiCont, helloCont, thereCont };
for (int x = 0; x < getContainsValue.length; x++) {
getContainsValue[x].setString(containsValue[x]);
}
Well you can use this.
Map<String,String> map = new HashMap<String,String>();
String[] str = {"hi","hello","there"};
for(int x = 0; x < str.lenght;x++){
map.put(str[x],"something you want to store");
}
Best thing may be use Map and store as key-Value pairs.
Map<String,String> myKVMap=new HashMap<String,String>();
myKVMap.put("strHi","value1");
myKVMap.put("strHello","value2");
myKVMap.put("strThere","value3");
This way you can eliminate all the variable name and value issues.
I think you should use Collection like Map.
Map is used to store data in the form of Key-Value Pairs.
Assume the Key is String and Value is a String too in your case.
Map<String, String> mp = new Map<String, String>();
mp.put("str1","Hi");
mp.put("str2","Hello");
You can iterate over it like the below.
for(Map.Entry<String, String> ar : mp.entrySet()){
System.out.println("Key: "+ar.getKey()+" :: "+"Value: "+ar.getValue());
}
Using a Map is a good idea. Another approach is to instantiate class variables, then assigning values will work.
public void testTransfer() {
String containsValue[] = { "hi", "hello", "there" };
Data strHi = new Data();
Data strHello = new Data();
Data strThere = new Data();
Data[] getContainsValue = { strHi, strHello, strThere };
for (int x = 0; x < getContainsValue.length; x++) {
getContainsValue[x].value = containsValue[x];
}
// print out
System.out.println(strHi.value);
System.out.println(strHello.value);
System.out.println(strThere.value);
}
class Data {
private String value;
}
There is no simple way to do what you want to do in Java. What you would need is the equivalent of the C / C++ address-of operator (&) ... or maybe Perl's ability to use a string as a variable name. Neither of these are supported in Java.
In theory, if the variables where instance variables, you could use reflection to access and update them. But the code to do this is messy, inefficient and fragile. And it won't work with local variables.
You would be better off looking for a different solution to the problem; e.g. use a Map, as other answers have suggested.
Or just settle for some clunky (but robust and reasonably efficient) code that uses a switch or series of if else if tests and the original variables.
If I am understanding your question, you want to be able to assign a regular String variable by looking it up in an array first and then making the assignment.
I agree with the other responders that if you are finding this approach necessary, it is probably ill-advised. But in the spirit of pure Q&A, here's the way:
interface StringAssigner {
void assign( String strValue );
}
// ...
String strHi, strHello, strThere;
StringAssigner[] asaGetContainsValue = {
new StringAssigner() { #Override public void assign( String strValue ) { strHi = strValue; } },
new StringAssigner() { #Override public void assign( String strValue ) { strHello = strValue; } },
new StringAssigner() { #Override public void assign( String strValue ) { strThere = strValue; } }
};
// ...
for (int x = 0; x < asaGetContainsValue.length; x++) {
asaGetContainsValue[x].assign( containsValue[x] );
}
Just say no.
I do agree with the other answers here that this feels like a workaround for something, but without knowing what that something is I cannot suggest anything better.
To answer the question, though: you could, however, wrap the string in simple class and store the object references of that class in your array and strHi, strHello, and strThere. This way even when you change the string property inside the class, the class object itself does not change so you will see the behavior you are looking for.
Or, you can use a HashMap as others have suggested. In your case if you still want to use the getContainsValue array, you can store the keys:
Map<String,String> map = new HashMap<String,String>();
map.put("strHi","");
map.put("strHello","");
map.put("strThere","");
String[] containsValue = { "hi", "hello", "there" };
String[] getContainsValue = { "strHi", "strHello", "strThere" };
for (int x = 0; x < getContainsValue.length; x++) {
map.put(getContainsValue[x], containsValue[x]);
}
Then, map.get("strHi") would return "hi" as you expect.