Skip to content

Instantly share code, notes, and snippets.

@audacus
Last active October 11, 2016 22:46
Show Gist options
  • Save audacus/3ffa11e184d24869599e61b5d4763dea to your computer and use it in GitHub Desktop.
Save audacus/3ffa11e184d24869599e61b5d4763dea to your computer and use it in GitHub Desktop.
Example solution for stackoverflow question: http://stackoverflow.com/q/39986249/3442851
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/*
output:
** cones before **
label: bar
height: 13.37
radius: 4.2
found foo: false
found bar: true
found baz: false
** cones after **
label: bar
height: <random double>
radius: <random double>
*/
class ConeStuff {
List<Cone> cones = new ArrayList<>();
ConeStuff() {
doWork();
}
public static void main(String[] args) {
new ConeStuff();
}
void doWork() {
// add some cones to the list and do other fancy stuff
cones.add(new Cone("bar", 13.37, 4.2));
// ...
printCones("cones before");
// random for random values
Random random = new Random();
double height;
double radius;
// use method from task to search for labels
boolean found;
for (String label : new String[] {"foo", "bar", "baz"}) {
height = random.nextDouble() * 100;
radius = random.nextDouble() * 100;
found = findAndAdjustCone(label, height, radius);
System.out.println("found " + label + ": " + found);
}
// see if cones are changed
printCones("cones after");
}
// method to find and change cones
boolean findAndAdjustCone(String label, double height, double radius) {
// default is false
boolean found = false;
// iterate over all cones
for (Cone cone : cones) {
// if cone label equals the given label in the arguments...
if (cone.label.equals(label)) {
// set found to true
found = true;
// change values of cone
cone.height = height;
cone.radius = radius;
// break for-loop because cone was found
break;
}
}
// return if cone was found or not
return found;
}
void printCones(String title) {
System.out.println("\n** " + title + " **");
for (Cone cone : cones) {
System.out.println("label: " + cone.label + "\n" +
"height: " + cone.height + "\n" +
"radius: " + cone.radius + "\n");
}
}
// cone bean
class Cone {
String label;
double height;
double radius;
Cone(String label, double height, double radius) {
this.label = label;
this.height = height;
this.radius = radius;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment