I have a method that requires a String[] for some details but after putting these details in how do I get them out one by one?
new String[] otherDetails = {"100", "100", "This is a picture"};
now in the picture I want to set the first string as the height, the second as the width, and the third as a description.
You refer to an element of an array by its index, like this:
height = otherDetails[0]; // 100
width = otherDetails[1]; // 100
description = otherDetails[2]; // This is a picture
You use the index to get the values
height = otherDetails[0];
width = otherDetails[1];
description = otherDetails[2];
Extract The details from array as follows :
height = otherDetails[0]; // 100
width = otherDetails[1]; // 100
description = otherDetails[2]; // This is a picture
Then call your method MyFunction(String heigth,String width,String description);
The index comments are probably what you're looking for, but you can also iterate through the elements using a loop.
int arraySize = stringArray.length;
for(int i=0; i<arraySize; i++){
if(i==0)
height = stringArray[i]; //do stuff with that index
}
This isn't the "right" approach for your particular problem, but I think it might help you understand ways that you can access items inside an array.
Side note, you could use alternative syntax:
String[] array = new String[3];
//fill in array
for(String s : array){
//this cycles through each element which is available as "s"
}
Related
This is a peice of my code, i am making a grid of 5x5 with random colors set to each section. I need to set the specified y_loc and x_loc in the list to the color randomly picked except i have not been able to find out how. It should be the second last line that is not operating as id like. I understand that i could do this in much much longer code but it would be nice to do it in less.
//making the map
ArrayList<ArrayList<String>> fullmap = new ArrayList<ArrayList<String>>();
ArrayList<String> y_row_0 = new ArrayList<String>();
ArrayList<String> y_row_1 = new ArrayList<String>();
ArrayList<String> y_row_2 = new ArrayList<String>();
ArrayList<String> y_row_3 = new ArrayList<String>();
ArrayList<String> y_row_4 = new ArrayList<String>();
//adding each row
fullmap.add(y_row_0);
fullmap.add(y_row_1);
fullmap.add(y_row_2);
fullmap.add(y_row_3);
fullmap.add(y_row_4);
Random rn = new Random();
//loop to randomly pick colors then set them to their destined locations
for (int y_loc = 0; y_loc < 6; y_loc++){
for (int x_loc = 0; x_loc < 6; x_loc++){
colorPicked = false;
while (!colorPicked){
int ranNum = rn.nextInt();
if (ranNum ==0){
if (redTot < 5) {
redTot += 1;
fullmap.set(y_loc).set(x_loc, "Red"));
colorPicked = true;
Since you have lists in list here, to set something at a specific location, you'll have to get the inner list and then perform the set on it.
The following should work:
fullmap.get(y_loc).set(x_loc, "Red"));
Also, since you seem to always have a 5x5 matrix, I'd recommend using a double array instead. That'd make that line:
fullmap[x_loc][y_loc] = "Red";
You should have something like this:
fullmap.get(y_loc).set(x_loc, "Red"));
Notice the "get". You are "getting" the list at the y location, which returns an array list, then calling "set" against that array list to set the actual value in the index of the "x_loc" value.
You need to make a couple of changes:
While declaring the sub lists, you need to make sure they have 5 empty/null elements. Otherwise set will throw IndexOutOfBoundsException. E.g. you need to declare the lists like this:
ArrayList<String> y_row_0 = Arrays.asList(new String[5]);//Assuming it will have 5 elements
While setting the element, you first need to get the corresponding sub list, e.g. the following needs to be changed from:
fullmap.set(y_loc).set(x_loc, "Red"));
to
fullmap.get(y_loc).set(x_loc, "Red"));
Others have already discussed the indexing issue. Apart from that, I believe that your conditionals may not be executing as you expect. nextInt() will return a reasonable uniform random number in the range of -2147483648 to 2147483647. You have a 1/2^64 chance of getting a 0. Reduce the random number range to something more reasonable. For example, nextInt(10) will return a random number between 0 and 9.
Furthermore, if the probability is too low, you will not get 5 reds all the time. To guarantee 5 picks and for the sake of computational efficiency, it is better to randomly pick array indices and evaluate whether a color is set or not, such as the following pseudo-code
int redTot = 0;
while ( redTot < 5 ) {
int r = rn.nextInt( 5 );
int c = rn.nextInt( 5 );
String color = fullmap.get( r ).get( c );
if ( color == null ) {
fullmap.get( r ).set( c, "Red" );
redTot++;
}
}
for(int i = 0; i < bag.length; i++)
{
if(bag[i].equals(a))
{
tmp = bag[i];
bag[i] = bag[bag.length-1];
bag[bag.length-1] = tmp;
numElements--;
break;
}
}
The goal of this is to find an object in the array and then remove it? is it possible??
Changing the length of an array is not possible. Recall that array is a static data structure whose size is determined before hand. Increasing or decreasing is not supported in this data structure. The fact that one has to increase or decrease the size depending on the usecase means that they have picked up the wrong data structure. They should perhaps go with an ArrayList.
Anyway, coming back to your question, you can simulate the 'size decrease' by maintaining a variable which you let track the array index and decrease the size of this variable. This lets you give the impression of shrinking the array.
The code you have provided does the same. Note however, that you should be using this modified index to track the contents of your array.
for(int i = 0; i < bag.length; i++)
{
if(bag[i].equals(a))
{
tmp = bag[i];
bag[i] = bag[bag.length-1];
bag[bag.length-1] = tmp;
numElements--;
break;
}
}
Whenever a particular bag at a given index equals to the item under question i.e., 'a', we swap elements so that the current bag element to be removed moves to the last and also we reduce the size of our new index - numElements by 1 to simulate this.
If you have the full code with you, please consider adding the following snippet at the end of that program to understand this more:
// Simulation of the array shrinking.
for(int i = 0; i < numElements; i++)
{
System.out.println( bag[i] );
}
// Movement of uninteresting elements to the end of the array.
for(int i = 0; i < bag.length; i++)
{
System.out.println( bag[i] );
}
It's not possible to change the length of an array. You can overwrite the element you wish to remove with the last element of the array and then copy the first bag.length - 1 elements of your array to a new array whose length is bag.length - 1.
for(int i = 0; i < bag.length; i++) {
if(bag[i].equals(a)) {
bag[i] = bag[bag.length-1];
bag = Arrays.copyOf (bag, bag.length - 1);
break;
}
}
public static String[] removeElements(String[] input) {
List<String> result = new ArrayList<String>();
String deleteValue = "somevalue";
for(String item : input)
if(!deleteValue .equals(item))
result.add(item);
return result.toArray(input);
}
This is one method you can fit this into your program.
You cannot decrease the size of an array. okay no problem! you can create your own data structure which supports that right?
Now, create a class named say MyArray with functions like increaseLenght(int) and decreseLength(int). Try it if you want to, will be fun for sure..
You cannot reduce the size of an array. Arrays are fixed length. What you can do is have a variable that indicates how many entries of the array you are using. This is what you are doing with numElements. The standard class ArrayList is implemented like this. The data is kept in an array and a private field size is used. With an ArrayList, when you remove an element, all the elements to the right are shifted left. However I also like your idea.
I would suggest 2 changes.
Make the last element null instead. If you are removing the element, why does it still need to be in the array?
Use numElements - 1 rather than bag.length-1 as the array could be bigger.
With these changes it becomes:
for(int i = 0; i < bag.length; i++)
{
if(bag[i].equals(a))
{
bag[i] = bag[numElements-1];
bag[numElements-1] = null;
numElements--;
break;
}
}
I have some code like this:
void drawPlot()
{
String[] dataItemPrices = loadStrings("itemPrices.csv"); //load in .csv file, store as string array
itemName = new String[dataItemPrices.length-1];
itemPrice = new float[dataItemPrices.length-1];
for (int i=0; i<dataItemPrices.length-1; i++)
{
//split array to consider commas
String[] tokensItemPrices = dataItemPrices[i+1].split(",");
itemName[i] = tokensItemPrices[0];
itemPrice[i] = Float.parseFloat(tokensItemPrices[1]);
dataMin = min(dataMin,itemPrice[i]);
dataMax = max(dataMax,itemPrice[i]);
itemPriceScaled = new float[map(itemPrice[i], dataMin, dataMax,
0, (height-100))];
}
}
The last line of code is causing problems, when I compile I get "cannot convert from float to int".
The only int is the [i] but that's used to access an array, it can't be that can it? Otherwise how can I access the array?
Help please!
Thanks!
There are a few possible alternatives:
You are creating a new float array and you need an int size for it, does map return a float? If this is the case, map could need major modifications.
What kind of parameters does map need? itemPrice[i], dataMin and dataMax are all floats(height could be too), is this correct? In this case, a cast to (int) could be enough or your function prototype needs to be fixed...
Please add the code for map and all variables declarations to your question.
Edit:
After your comment and looking at your code, maybe this is what you want to do: populating an array with prices (taken from the itemPrice array) "scaled" using map that has obviously the same size as the other two arrays:
void drawPlot()
{
String[] dataItemPrices = loadStrings("itemPrices.csv"); //load in .csv file, store as string array
itemName = new String[dataItemPrices.length-1];
itemPrice = new float[dataItemPrices.length-1];
itemPriceScaled = new float[dataItemPrices.length-1]; // <<<<<Added
for (int i=0; i<dataItemPrices.length-1; i++)
{
//split array to consider commas
String[] tokensItemPrices = dataItemPrices[i+1].split(",");
itemName[i] = tokensItemPrices[0];
itemPrice[i] = Float.parseFloat(tokensItemPrices[1]);
dataMin = min(dataMin,itemPrice[i]);
dataMax = max(dataMax,itemPrice[i]);
itemPriceScaled[i] = map(itemPrice[i], dataMin, dataMax,
0, (height-100)); //<<<Modified
}
}
How the array size is auto increment in java program my requirement is "create a 2 dimensional array
sno, in the first dimension
name, age in the second dimension
so if i pass sds, 25
it should be added to the array [0][sds,25]
the array should keep incrementing"
my code is like this:
void values() throws IOException{for ( int row = i; row < len; row++ ){
for ( int column = 1; column <= 1; column++ ){
arrayValues[row][0] = String.valueOf(row+1);
System.out.print("Enter "+(row+1)+" Name: ");
String name = br.readLine();
System.out.print("Enter "+(row+1)+" age: ");
int age = Integer.parseInt(br.readLine());
arrayValues[row][column]= name+","+age;
}
void incrementSize() throws IOException{String[][] newArray = new String[arrayValues.length][];
System.out.println(newArray.length);
String[][] t = Arrays.copyOf(arrayValues, newArray.length);
After this how can done my code Please help me
I think the perfect bet of your requirement is ArrayList.
Resizable-array implementation of the List interface.
You have to create a new array in order to make the size bigger, there is no dynamic way to increase an existing array.
Here is a way you can create a new array to increase the size.
int[] a = new int[5];
// fill a
int[] b = Arrays.copyOf(a, 10);
Use List for this requirement. You can use a ArrayList<ArrayList> in place of 2-dim array. ArrayList is Resizable-array implementation of the List interface.
An array is a container object that holds a fixed number of values of a single type.
Sounds like you are looking a dynamically growing data structure. you can use implementation of list interface which is in java collection frame work. you can use ArrayList or Vectors.
Using java.util.Arrays class it is possible. Please refer below link for answer.
How to increase string array size automatically or dynamically
I have a String[] that contains number of strings, what I'm trying to do is set a ProgressBar's progress according to which string is used.
For example, I have already determined number of strings and set max progress of progress bar accordingly; here is the list:
"zero one two three four five six seven eight nine...."
..
String[] cpu0freqslist = cpu0freqs.split("\\s");
countcpu0 = cpu0freqslist.length;
..
ProgressBar cpu0progbar = (ProgressBar)findViewById(R.id.progressBar1);
cpu0progbar.setMax(countcpu0);
But now I need to set the progress of progressbar according to the item that is used, and I don't know how to get item position.
So if I want to set a progress bar to the position of item five (in this case it would be 6) how can I do that - how can I get the position of item five?
essentially what you're looking for is a indexOf(...) ...
since arrays don't have it, you'll have to search thru it to find the desired string. so something like this (feel free to optimize)
public int indexOfString(String searchString, String[] domain)
{
for(int i = 0; i < domain.length; i++)
if(searchString.equals(domain[i]))
return i;
return -1;
}
Then again, if you dynamically fetch your String[] data, it would be wiser to use an ArrayList and just invoke list.indexOf(myString);
You can use the Arrays utility class:
List<String> list = Arrays.asList(new String[] {"First", "Second", "Third"});
int index = list.indexOf("Second"); // 1
cpu0freqslist[5]
Does this help you?
Ok let me break your query into parts...
String[] arr = {"First","Second","Third"}; // String array with 3 elements
for(int i=0 ; i<arr.length ; i++){
int j = i ; // Position of the element
String s = a[i] ; // Element Itself
System.out.println("The "+i+" element is "+s);
}