App reads TextEdit value to String and then converts to ArrayList. But before converting it removes spaces between words in TextEdit. So after converting I get ArrayList size only 1.
So my question is how to get the real size. I am using ArrayList because of its swap() function.
outputStream.setText("");
stream = inputStream.getText().toString().replace(" ", "");
key = Integer.parseInt(inputKey.getText().toString());
List<String> arrayList = Arrays.asList(stream);
int lenght = arrayList.size();
if (key < lenght)
{
outputStream.append(lenght+"\n");
outputStream.append("OK");
}
else {
outputStream.append(lenght+"\n");
outputStream.append("Error");
}
}
stream = inputStream.getText().toString();
key = Integer.parseInt(inputKey.getText().toString());
List<String> arrayList = new ArrayList<String>();
for (String x : stream.split(" ")) arrayList.add(x);
int lenght = arrayList.size();
if (key < lenght)
{
outputStream.append(lenght+"\n");
outputStream.append("OK");
}
else {
outputStream.append(lenght+"\n");
outputStream.append("Error");
}
That is my guess at what you actually wanted to do...
The size and the length are different things.
You try to get the size when you want the length.
Use arrayList[0].length() instead of your arrayList.size().
If you want to parse your String to an Array try:
List<String> arrayList = Arrays.asList(stream.split(","));
(this example expects that your text is a comma separated list)
Arrays.asList() expect an array as paramter not just a String. A String is like an array of String of size 1 thats why your list is always of size 1. If you want to Store the words of your String use :
Arrays.asList(stream.split(" ")); //Don't use replace method anymore
Related
I am receiving a response from the server in an ArrayList of String. Now how can I set those strings on TextView? The size of the ArrayList is unknown.
Solution
When you do get the response from the server then you know the size of the ArrayList so try this method I think it should do the trick!
public void setTextViewValues (ArrayList<String> vals, TextView text) {
//Variable to hold all the values
String output = "";
for (int i = 0; i < vals.size(); i++) {
//Append all the values to a string
output += vals.get(i);
}
//Set the textview to the output string
text.setText(output);
}
Just add all values to one string value
String result = "";
for (String s : arrayList) {
result +=s;
}
And then set it
textView.setText(result);
What exactly you mean?
Display it in a row?
StringBuilder builder = new StringBuilder();
for(String s : arrayListName){
builder.append(s+" ,");
}
textView.setText(builder.toString());
you can simply convert your arry of string into a string with the method
Arrays.toString(YourArray);
wich will convert your arry into a string
then you simply put it in the textView.setText like this
textView.setText(Arrays.toString(YourArray));
And if you want it displayed without the special character you can just add this
textView.setText(Arrays.toString(YourArray).replaceAll("\\[|\\]", ""));
I have to put in a string array some values resulting from several parsed html pages. So the first value it's a name and all the others are numbers. After I must return the array to main to print. Obviously I make something wrong .
this is part of my newbie code...
String[] ret = null;
int y = 0;
for (Element h1 : h1s) {
// Using Jsoup to scrape the html file and find H1 text
h1_id = h1.className();
// I put here the text of H1
h1_text = h1.text();
if (h1_id.equals("ezomat-logo-text ezCSS")) {
// jump to the next h1
} else {
// I want to put the txt as the first array place
ret[y] = "'" + h1_text + "'";
}
i = 0;
// found the number values single integers with comma
for (Element image : images) {
Imm[i] = "," + imageName;
i++;
}
i = 0;
y = 1;
// y = 1 because I want to start from the second position.
for (Element image : images) {
ret[y] = Imm[i];
i++;
y++;
}
}
return ret;
You can't dynamicly resize an array, you have to initialize it with a fixed size.
So, you have to initialize it with
String[] ret = new String[size];
where size have to be the number of elements you are going to put into your array.
Or the better approach: Use ArrayList<String>instead. Initialize it with
ArrayList<String> ret = new ArrayList<String>();
and add your Items with ret.add("whatever");.
On the first line of your code you attempt to define an array without a size, but you don't actually define it, you just assign null.
Also, it's impossible to dynamically add elements to such array.
For these scenarios we have List.
To define a List that stores Strings use the following code:
List<String> ret = new ArrayList<String> ();
And then proceed to add elements to this array like so:
ret.add ("," + imageName);
To retrieve a value from an index in the list do the following:
ret.get(index);
Java does not allow arrays with variable length. I think that this is your main problem.
There are two choiches:
Obtain the array length first and instantiate the array accordingly
String[] ret = new String[100];
Use an ArrayList
ArrayList<String> ret = new ArrayList<String>();
You can add elements to the ArrayList like this: ret.add(value);
The Java Tutorial: Arrays
java.util.ArrayList reference
I have an array like this :
String[] array = { "Designation1", "Designation2", "Designation3" };
If user put "Designation2" as input then the code should return 1.
It may be very simple question, but I am very new in Java. So please give some suggestions.
Consider using List instead of array (of just wrap your array in List). This way you will have access to method like indexOf(element) which will return index of first founded element, of -1 if no element in array was found.
String[] array = { "Designation1", "Designation2", "Designation3" };
List<String> list = Arrays.asList(array);
System.out.println(list.indexOf("Designation2")); //prints 1
System.out.println(list.indexOf("foo")); //prints -1
You can loop over the Strings in the array and find the index for which the String matches what you are looking for.
int index = -1;
for (int i=0; i<array.length;i++) {
if (array[i].equals(value)) {
index = i;
break;
}
}
You could just use a for loop
String[] array = { "Designation1", "Designation2", "Designation3" };
Scanner kb=new Scanner(System.in);
String input=kb.next();
int index;
for(int i=0;i<array.length;i++)
{
if(array[i].equalsIgnoreCase(input))
index=i;
}
You can do it like this.
String userinput="Designation2";
String[] array = { "Designation1", "Designation2", "Designation3" };
int length=array.length();
int index=0;
for(int i=0;i<length;i++)
{
if(array[i].equals(userinput))
{
index=i;
break;
}
}
And index will give you the array key that user wants.
Regards..
There are no direct search method for array so you need to convert it to list first
String[] array = { "Designation1", "Designation2", "Designation3" };
assert Arrays.asList(array).indexOf("Designation2") == 1;
assert Arrays.asList(array).indexOf("Anything else") == -1;
Do not forget that -1 mean 'not found'
Or you can sort it and use binarySearch
You can use ArrayUtils from Apache Commons.
String[] array = { "Designation1", "Designation2", "Designation3" };
System.out.println(ArrayUtils.indexOf(array, "Designation1"));//0
System.out.println(ArrayUtils.indexOf(array, "Designation2"));//1
System.out.println(ArrayUtils.indexOf(array, "Designation3"));//2
In order to do this task, you can use two arrays, one for key names and ones for their values. Simply search for the key in the first array, get the index of the key name and use it to get the value from the second array. It's not the most efficient, and this is probably not the best answer, but it works for me.
Just make sure the indexes in the arrays line up, for example:
{"my","three","keys"};
{"My","Three","Values"};
In this case, the key/value setup would be;
my/My
three/Three
keys/Values
In your case, you don't need to use the value array, just use the index.
Also try using ArrayList instead of arrays, as you can use ArrayList.indexOf(key) to get the index of key in the ArrayList.
Hope this helps you and others with this problem. ☺
I am creating a program that lets you store 10 items in an array. What I haven't been able to get the program to do is give an error if one of the entered items already exists in the array.
So, for example, if the array looks like [banana, potato, 3, 4, yes, ...] and I enter banana again, it should say "Item has already been stored" and ask me to re-enter the value. The code I currently have is:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int stringNumber = 0;
String[] stringArray = new String[10];
for (int i = 0; i <= stringArray.length; i++) {
out.println("\nEnter a string");
String input = keyboard.next();
stringArray[stringNumber] = input;
out.println("\"" + stringArray[stringNumber] + "\"" + " has been stored.");
PrintArray(stringArray);
stringNumber++;
You can use nested loops to go through the array to see if the new input exists. It would be better to do this in a function. Also when doing this you need to make sure that you are not at the first element or you will get a null pointer exception.
for (int i = 0; i <= stringArray.length; i++) {
boolean isInArray = false;
System.out.println("\nEnter a string");
String input = keyboard.next();
if (i > 0) {
for (int j = 0; j < stringArray.length; j++) {
if (stringArray[j].equalsIgnoreCase(input)) {
isInArray = true;
break;
}
}
}
if (!isInArray) {
stringArray[stringNumber] = input;
} else {
System.out.println("\"" + stringArray[stringNumber-1] + "\""
+ " has been stored.");
}
PrintArray(stringArray);
stringNumber++;
}
It's always better to use a HashSet when you don't want to store duplicates. Then use HashSet#contains() method to check if element is already there. If ordering is important, then use LinkedHashSet.
If you really want to use an array, you can write a utility method contains() for an array. Pass the array, and the value to search for.
public static boolean contains(String[] array, String value) {
// Iterate over the array using for loop
// For each string, check if it equals to value.
// Return true, if it is equal, else continue iteration
// After the iteration ends, directly return false.
}
For iterating over the array, check enhanced for statement.
For comparing String, use String#equals(Object) method.
When you got the String input, you can create a method that will :
Go through the entire array and check if the string is in it (you can use equals() to check content of Strings)
Returns a boolean value wheter the string is in the array or not
Then just add a while structure to re-ask for an input
Basically it can look like this :
String input = "";
do {
input = keyboard.next();
}while(!checkString(input))
The checkString method will just go through all the array(using a for loop as you did to add elements) and returns the appropriate boolean value.
Without introducing some order in your array and without using an addition structure for instance HashSet, you will have to look through the whole array and compare the new item to each of the items already present in the array.
For me the best solution is to have a helper HashSet to check the item for presence.
Also have a look at this question.
To avoid you should use an Set instead of an array and loop until size = 10.
If you need to keep an array, you can use the .contains() method to check if the item is already present in the array.
while (no input or duplicated){
ask for a new string
if (not duplicated) {
store the string in the array
break;
}
}
You should check the input value in array before inserting into it. You can write a method like exists which accepts String[] & String as input parameter, and find the string into the String array, if it finds the result then return true else false.
public boolean exists(String[] strs, String search){
for(String str : strs){
if(str.equals(search))
return true;
}
return false;
}
performance would be O(n) as it searchs linearly.
I have a set in Java looks like
[0.99998945, line10Rule:14013, noOfCommits:0]
and, I want to remove all digital numbers and colon ':' from its element to get
[line10Rule, noOfCommits]
What is the best way to do that?
Now corrected:
String[] array = new String[set.size()]; // create a String array of the same size as the set
set.toArray(array); // copy the sets content into the array
set.clear(); // clear the set
for (String string : array) { // iterate through the array
set.add(string.replaceAll("[0-9]*$", "")); // remove the digits and put the resulting String back into the set
}
#jlordo: thanks for pointing it out. I forgot, that the iterator works on a copy of the String. This may not be elegant (iterating through so many loops etc) but it works :D
regards Christoph
Try this
List<String> list = new ArrayList<String>(Arrays.asList("0.99998945", "line10Rule:14013", "noOfCommits:0"));
ListIterator<String> i = list.listIterator();
while(i.hasNext()) {
String s = i.next();
int p = s.indexOf(':');
if (p > 0) {
i.set(s.substring(0, p));
} else {
i.remove();
}
}
System.out.println(list);
output
[line10Rule, noOfCommits]
No way, you will have to recreate the set item by item. To replace numbers with "", consider String.replace().