I'm taking care of some other methods and I don't know what to do with this one. I want to change the order of the string inside the array (not the order of the string*s*), but this isn't accepted. Any ideas?
public void invert() {
for(int i = 0; i < array.length; i++){
for(int j = 0, k = array[i].length() - 1; j < k; j++, k--){
char a = array[i].charAt(j);
array[i].charAt(j) = array[k].charAt(k); //ERROR HERE
array[i].charAt(k) = a; //AND HERE
}
}
}
EDIT: I'll leave here what I mean.
I have an array = {"Hello", "Goodbye"}
I want to change it to {"olleH", "eybdooG"}
Java string are immutable. You can't change them.
(But you can convert the string to a StringBuilder - http://docs.oracle.com/javase/tutorial/java/data/buffers.html - which is essentialy a mutable string, change the characters, and then convert the StrignBuilder back to String.)
Try this code (I haven't tested it, but I hope it works):
for(int i = 0; i < array.length; i++) {
StringBuilder b = new StringBuilder(array[i]);
for(int j = 0, k = b.length() - 1; j < k; j++, k--){
char a = b.charAt(j);
b.setCharAt(j, array[k].charAt(k));
b.setCharAt(k, a);
}
array[i] = b.toString();
}
array[i].charAt(j) = array[k].charAt(k); //ERROR HERE
array[i].charAt(a) returns a value not a variable. You are trying to assign a value to a value which doesn't make any sense.
java String is immutable. You can't change it.
Use StringBuilder which has setCharAt(int index,
char ch); function which is what you are probably wanting.
The most simple way is, to reverse letter with StringBuilder.reverse() method. Try,
for(String str : array){
System.out.println(new StringBuilder(str).reverse());
}
Just use this on every String in your array:
String reversed = new StringBuilder(stringFromArray).reverse().toString();
try doing new StringBuilder(array[i]).reverse().toString();
you would have to create a substring.
array[i]= array[i].substring(0,j) + array[k].charAt(k) + array[i].substring(j+1);
This would do the required edit i beleive
Related
This code is to get the occurrence of the characters in the Arraylist firlast but charAt can't be used and gives an error
The method charAt(int) is undefined for the type ArrayList<String>Java(67108964)
int len = firlast.size();
int count[] = new int[256];
for(int i = 0; i < len; i++)
count[firlast.charAt(i)]++;
char ch[] = new char[firlast.size()];
for (int i = 0; i < len; i++) {
ch[i] = firlast.charAt(i);
int find = 0;
for (int j = 0; j < i; j++) {
if (firlast.charAt(i) == ch[j])
find++;
}
if (find == 1)
System.out.println("occurence " + firstlast.charAt(i) + count[firstlast.charAt(i)]);
}
Output of the firlast array is [rj, yf, rC, ac, ps, ni, er, et, FT, ei]
I dont know what i did wrong. please point out where i did wrong.
There is no charAt method on an ArrayList. The closest is List.get(int) which returns the list element at a given position.
However, in your example you have an ArrayList<String>, so get will return a String rather than a character, and you can't use a string as an array index.
Unfortunately, I think the real problem here is that ArrayList<String> is the wrong data structure for this code. Better alternatives might be char[], ArrayList<Character> String or StringBuilder. It is hard to say without more context.
I have a 2D String array freq:
String freq[][] = new String[26][2];
and I would like to use the contents of the first column only with new String(freq) which would work if freq is a normal array. However I would like to do this with the first column of my 2D array, or would I have to use two 1D arrays to do this:
String freq[][] = new String[26][2];
int free = 0;
for (int b = 0; b < words.length; b++) {
for (int l = 0; l < words[b][0].length(); l++) {
if (new String(freq[0]).indexOf(words[b][0].charAt(l)) < 0) {
freq[free][0] = Character.toString(words[b][0].charAt(l));
free++;
}
}
}
Thanks! :)
Use a StringBuilder and concat all the values (replace 8 with whatever your average word length is):
final StringBuilder builder = new StringBuilder(words.length * 8);
for (String[] nestedWords : words)
{
builder.append(nestedWords[0]);
}
return builder.toString();
You could also do this in java 8 as so:
return Arrays.stream(words).map(a -> a[0]).collect(Collectors.joining());
I'm not quiet sure if I understand what you want to achive but if you only want to iterate over the first column just do something like this and just drop the inner loop
for(int i = 0; i < words.length; i++) {
//Do stuff with words[i][0], e.g.
words[i][0] = Some_usefull_thing;
}
I would like display the values of my String array in one Jlabel.
I've tried with a loop (for) but, the result is the new letter overwrites the previous.
I do not understand how I could displaying the letters following.
labelWord is the variableName of my Jlabel.
String myArray[] = new String[4];
myArray[0] = "h";
myArray[1] = "e";
myArray[2] = "l";
myArray[3] = "l";
myArray[4] = "o";
and my loop :
for (int j = 0; j <= myArray.length; j++) {
labelWord.setText(myArray[j]);
}
You are replacing the text each time you call labelWord.setText().
Just build the whole string before you set it
StringBuilder builder = new StringBuilder();
for (int j = 0; j <= myArray.length; j++) {
builder.append(myArray[j]);
}
labelWord.setText(builder.toString());
Your code does not work because you set the label value with the 1st String, then the second one, then the 3rd one... You need to concatene all your String into one then set the label text with this value:
String value ="";
for (int j = 0; j <= myArray.length; j++) {
value += myArray[j];}
labelWord.setText( value );
Note: you can also use a StringBuilder instead of concatenating directly to the String.
You are overwriting it yourself by calling setText() everytime in loop. you need to append it to the text by doing:
labelWord.setText(labelWord.getText() + myArray[j]);
Hope this helps.
The easiest way to do this without using StringBuilder or anything like that would be to use another string variable
String myLabelText = "";
for (int j = 0; j <= myArray.length; j++) {
myLabelText = myLabelText + myArray[j];
}
labelWord.setText( myLabelText );
You were essentially just changing the value of the label for every item in the array, not adding it to the end
One More Interesting Way you would like to know(In your CASE)
String arr[]={"h","e","l","l","o"};
System.out.println(Arrays.toString(arr).replaceAll("[\\]\\[,\\s]", ""));
OUTPUT
hello
So directly,
jlabel.setText(Arrays.toString(arr).replaceAll("[\\]\\[,\\s]", ""));
NOTE:
This will not be applicable if array elements contains space(Sorry for that).
I'm doing a project for Java 1, and I'm completely stuck on this question.
Basically I need to double each letter in a string.
"abc" -> "aabbcc"
"uk" -> "uukk"
"t" -> "tt"
I need to do it in a while loop in what is considered "Java 1" worthy. So i'm guessing that this means more of a problematic approach.
I know that the easiest way for me to do this, from my knowledge, would be using the charAt method in a while loop, but for some reason my mind can't figure out how to return the characters to another method as a string.
Thanks
[EDIT] My Code (wrong, but maybe this will help)
int index = 0;
int length = str.length();
while (index < length) {
return str.charAt(index) + str.charAt(index);
index++;
}
String s="mystring".replaceAll(".", "$0$0");
The method String.replaceAll uses the regular expression syntax which is described in the documentation of the Pattern class, where we can learn that . matches “any character”. Within the replacement, $number refers to numbered “capturing group” whereas $0 is predefined as the entire match. So $0$0 refers to the matching character two times. As the name of the method suggests, it is performed for all matches, i.e. all characters.
Yeah, a for loop would really make more sense here, but if you need to use a while loop then it would look like this:
String s = "abc";
String result = "";
int i = 0;
while (i < s.length()){
char c = s.charAt(i);
result = result + c + c;
i++;
}
You can do:
public void doubleString(String input) {
String output = "";
for (char c : input.toCharArray()) {
output += c + c;
}
System.out.println(output);
}
Your intuition is very good. charAt(i) will return the character in the string at location i, yes?
You also said you wanted to use a loop. A for loop, traversing the length of the list, string.length(), will allow you to do this. At every single node in the string, what do you need to do? Double the character.
Let's take a look at your code:
int index = 0;
int length = str.length();
while (index < length) {
return str.charAt(index) + str.charAt(index); //return ends the method
index++;
}
Problematically for your code, you are returning two characters immediately upon entering the loop. So for a string abc, you are returning aa. Let's store the aa in memory instead, and then return the completed string like so:
int index = 0;
int length = str.length();
String newString = "";
while (index < length) {
newString += str.charAt(index) + str.charAt(index);
index++;
}
return newString;
This will add the character to newString, allowing you to return the entire completed string, as opposed to a single set of doubled characters.
By the way, this may be easier to do as a for loop, condensing and clarifying your code. My personal solution (for a Java 1 class) would look something like this:
String newString = "";
for (int i = 0; i < str.length(); i++){
newString += str.charAt(i) + str.charAt(i);
}
return newString;
Hope this helps.
try this
String a = "abcd";
char[] aa = new char[a.length() * 2];
for(int i = 0, j = 0; j< a.length(); i+=2, j++){
aa[i] = a.charAt(j);
aa[i+1]= a.charAt(j);
}
System.out.println(aa);
public static char[] doubleChars(final char[] input) {
final char[] output = new char[input.length * 2];
for (int i = 0; i < input.length; i++) {
output[i] = input[i];
output[i + 1] = input[i];
}
return output;
}
Assuming this is inside a method, you should understand that you can only return once from a method. After encountering a return statement, the control goes back to the calling method. Thus your approach of returning char every time in a loop is faulty.
int index = 0;
int length = str.length();
while (index < length) {
return str.charAt(index) + str.charAt(index); // only the first return is reachable,other are not executed
index++;
}
Change your method to build a String and return it
public String modify(String str)
{
int index = 0;
int length = str.length();
String result="";
while (index < length) {
result += str.charAt[index]+str.charAt[index];
index++;
}
return result;
}
Suppose some situations exist where you would like to increment and decrement values in the same for loop. In this set of situations, there are some cases where you can "cheat" this by taking advantage of the nature of the situation -- for example, reversing a string.
Because of the nature of building strings, we don't really have to manipulate the iterate or add an additional counter:
public static void stringReversal(){
String str = "Banana";
String forwardStr = new String();
String backwardStr = new String();
for(int i = str.length()-1; i >= 0; i--){
forwardStr = str.charAt(i)+forwardStr;
backwardStr = backwardStr+str.charAt(i);
}
System.out.println("Forward String: "+forwardStr);
System.out.println("Backward String: "+backwardStr);
}
However, suppose a different case exists where we just want to print a decremented value, from the initial value to 0, and an incremented value, from 0 to the initial value.
public static void incrementAndDecrement(){
int counter = 0;
for(int i = 10; i >= 0; i--){
System.out.println(i);
System.out.println(counter);
counter++;
}
}
This works well enough, but having to create a second counter to increment seems messy. Are there any mathematical tricks or tricks involving the for loop that could be used that would make counter redundant?
Well it looks like you just want:
for(int i = 10; i >= 0; i--){
System.out.println(i);
System.out.println(10 - i);
}
Is that the case? Personally I'd normally write this as an increasing loop, as I find it easier to think about that:
for (int i = 0; i <= 10; i++) {
System.out.println(10 - i);
System.out.println(i);
}
Note that your string example is really inefficient, by the way - far more so than introducing an extra variable. Given that you know the lengths involved to start with, you can just start with two char[] of the right size, and populate the right index each time. Then create a string from each afterwards. Again, I'd do this with an increasing loop:
char[] forwardChars = new char[str.length()];
char[] reverseChars = new char[str.length()];
for (int i = 0; i < str.length(); i++) {
forwardChars[i] = str.charAt(i);
reverseChars[reverseChars.length - i - 1] = str.charAt(i);
}
String forwardString = new String(forwardChars);
String reverseString = new String(reverseChars);
(Of course forwardString will just be equal to str in this case anyway...)
You can have multiple variables and incrementers in a for loop.
for(int i = 10, j = 0; i >= 0; i--, j++) {
System.out.println(i);
System.out.println(j);
}