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.
Related
String quantityArray[] = GetStringArray(quantity);
String foodItemArray[] = GetStringArray(fooditems);
this is to change from ArrayList to a String Array
int n1 = fooditems.size();
int n2 = quantity.size();
for(int s = 0; s<n1;s++){
totalFood[s] = quantityArray[s] + foodItemArray[s];
}
I cannot make this totalFood[] function to work as it just keeps crashing my app
public static String[] GetStringArray(ArrayList<String> arr) {
// declaration and initialise String Array
String str[] = new String[arr.size()];
// ArrayList to Array Conversion
for (int j = 0; j < arr.size(); j++) {
// Assign each value to String array
str[j] = arr.get(j);
}
return str;
}
The error that pops up is (Attempt to write to null array)
You need to make sure totalFood array is allocated.
Arrays are themselves Objects in Java.
For example:
totalFood = new String[n1];
This is because totalFood seems to be null according to the error you are seeing. You need to allocate some space (n1 references to be precise for the above example) for the Strings resulting from the concatenation to be stored at. You can take a look at the corresponding Java tutorial here.
Also make sure n1 is equal to n2 which should be equal also to the size of the totalFood array in order to not overrun any of them in your loop.
Finally, there are 2 handy Collection#toArray methods which will do what you are doing in your GetStringArray method. You can use it for example like so:
String quantityArray[] = quantity.toArray(new String[quantity.size()]);
Using the toArray method seems not to be related to the problem, but I just mention it for completeness.
public static String[] GetStringArray(ArrayList<String> arr) {
String str[] = new String[arr.size()];
for (int j = 0; j < arr.size(); j++) {
str[j] = arr.get(j);
}
return Arrays.stream(str).filter(s -> s!=null).toArray(String[]::new);
}
I need to make a generic function that takes an array of numbers (integers, doubles or whatever else), and then make a 2D array in which the first row is that array and every next row is the previous one squared. What I made gives me a
java.lang.object cannot be cast to java.lang.number
even though I put E extends Number. I tried the same function using just int and it does what I need it to do.
Where did I make a mistake? Am I using the "E extends Number" wrong?
public static<E> void napraviMatricu(E[] niz) {
int n = niz.length;
E[][] matrica = (E[][]) new Object[n][n];
for(int i = 0; i < matrica[0].length; i++)
matrica[0][i] = niz[i];
for(int i = 1; i < matrica.length; i++)
for(int j = 0; j < matrica[i].length; j++)
matrica[i][j] = matrica[i-1][j] * matrica[i-1][j];
for(int i = 0; i < matrica.length; i++) {
for(int j = 0; j < matrica[i]. length; j++)
System.out.print(matrica[i][j] + " ");
System.out.println("");
}
}
This is your problem:
E[][] matrica = (E[][]) new Object[n][n];
Do this (cls is of type Class<E>):
#SuppressWarnings("unchecked")
E[][] matrica = (E[][]) Array.newInstance(cls, n, n);
Reference
According to this link, Java generics are not designed in a way to perform arithmetic operations. I hope it helps you regarding generic methods and arithmetic operations:
Using a generic class to perform basic arithmetic operations
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
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);
}