I have a Vector full of longs.
I would like to be able to always call getFirstElement() on a Vector and then perform an action, let's say addToOtherVector(). I want to be able to not worry whether or not there is actually a value to return from my original vector. I think I could do it by overriding addToOtherVector() like so:
//Code to be called when my first vector is not empty
public void addToOtherVector(long s){
othervector.add(s);
}
//Code to be called when my first vector IS empty
public void addToOtherVector(something???){
//does nothing
}
but I'm not sure what i need to do for the something, as it won't accept null as a parameter?
The reason I am doing this is because I don't wish to have to check the size of the vector each time I try to retrieve
Just override the method with a base class. Since Number is the base class to Long, Integer, etc. just use that one :
//Code to be called when my first vector is not empty
public void addToOtherVector(long s){
othervector.add(s);
}
//Code to be called when my first vector IS empty
public void addToOtherVector(Number s){
if (s == null) {
return;
}
othervector.add(((Number) s).longValue());
}
import java.util.Vector;
public class Main {
static Vector otherVector = new Vector();
public static void main(String[] args) {
Vector originalVector = new Vector();
originalVector.add(1);
originalVector.add(null);
originalVector.add(2);
for (Object obj : originalVector) {
addToOtherVector(obj);
}
}
public static void addToOtherVector(long s) {
otherVector.add(s);
System.out.println("adding " + s + " to vector");
}
public static void addToOtherVector(Object obj) {
System.out.println("not adding " + obj + " to vector");
}
}
Related
So what I expected this code to display on console was
"hi"
"Ken is a legend"
"forkbomb"
public class ForkBombOnClick {
public static void main(String[] args) {
System.out.println("hi");
ken();
System.out.println("fork bomb");
}
public static String ken() {
return ("ken is a legend");
}
}
But instead it only displays hi and forkbomb. When I change it to public static void ken() then it returns what I wanted the value to be but I was wondering. Why doesn't this current code work?
You need to use the string returned by method ken(); like
System.out.println(ken());
Once a method returns something, you need to get hold of it to use it.
You can also use it like:
String returnValue = ken();
System.out.println(returnValue);
This will also yield same result.
You know the answer yourself!
Why do you use System.out.println? To print on the screen string that you pass to the function.
You do it correctly by System.out.println("hi");, so it prints hi.
Now, you want to print string returned by ken() method. It has string as return type, so you can think of ken(); invocation as a string. Just like hi.
So if you want to print it, you need to use System.out.println and supply result of ken() method to it, just like with other strings: System.out.println(ken());.
You should use return value in print statement which is string as "ken is a legend" .
Your final code should be like this ;
public class ForkBombOnClick {
public static void main(String[] args) {
System.out.println("hi");
System.out.println(ken());
System.out.println("fork bomb");
}
public static String ken() {
return "ken is a legend";
}
}
or more clear version of code ;
public class ForkBombOnClick {
public static void main(String[] args) {
System.out.println("hi" + "\n" + ken() + "\n" + "fork bomb");
}
public static String ken() {
return "ken is a legend";
}
}
In this System.out.println("hi" + "\n" + ken() + "\n" + "fork bomb");
\n refers to newline.
I have a problem with the following code:
Import java.util.ArrayList;
public class Car {
private String car;
private Car genCar = new Car();
ArrayList<String> allCars = new ArrayList<>();
public void setCar() {
genCar.setModel();
genCar.setCreator();
car = genCar.getModel() + "made by" + genCar.getCreator();
}
public void checkDouble() {
for (String search : allCars) {
while (search.equals(car)) {
setCar();
}
}
allCars.add(car);
}
public void repeater(){
for(int i = 0; i<52; i++){
setCar();
checkDouble();
}
}
}
Whenever I try to check for duplicates (which this code does) my program still puts the duplicate in the array when I actually try to avoid it this way.
Any solution so this works?
You do this:
public void checkDouble()
{
for (String search : allCars)
{
while (search.equals(car))
{
setCar();
}
}
allCars.add(car);
}
The problem with this is that, once you found a double, you generate a new car using setCar(), but you do not search the entire list again.
Do something like:
public void avoidDoubles()
{
while allCars.contains(car)
{
setCar(); // generate new, different car
}
allCars.add(car);
}
FWIW, you might want to change the name of some of the functions. I would call setCar() generateNewCar() or newCar().
I'm not sure what you're trying to do, but in checkDouble you are finding a duplicate and then adding it to the list.
If I understand you correctly, you don't need the loops, All you need to do is to use ArrayList.contains()
if(allCars.contains(someString))
{
System.err.println("Duplicate...");
} else
{
//setCar, addCar, etc.
}
My program is structured as follows: a class that represents an atomic concept which is essentially a String and another class that is made of a list of general concepts. Both classes extends the class Concept that is an abstract class, this means that in the list I could have both atomic concepts and intersection of concepts arbitrary nested.
Each concept, atomic or composed, is printed out by toString method.
Roughly speaking, this is based on this context-free grammar:
C : atom | (C and)+ C
Where C is the abstract class Concept, atom is AtomicConcept and (C and)+ C is Intersection.
This is the AtomicConcept class:
public class AtomicConcept extends Concept{
private String atomicConceptName;
public AtomicConcept(String c) {
this.atomicConceptName = c;
}
#Override
public String toString() {
return atomicConceptName;
}
}
This is che ConceptIntersection class:
import java.util.List;
public class ConceptIntersection extends Concept{
private List<Concept> list;
public ConceptIntersection(List<Concept> l) throws Exception {
if(l.size()>1)
{
this.list = l;
}
else
{
throw new Exception("Intersection needs at least two concepts!");
}
}
public String toString()
{
return Utils.conceptIntersection + Utils.lparen + Utils.splitConcepts(list) + Utils.rparen;
}
}
As you can see in toString function, I also created a method called splitConcepts that takes in input a list of general concepts and returns one string made of each concept separated by comma.
public static String splitConcepts(List<Concept> list)
{
String result = "";
for (Concept item : list) {
System.out.println(item);
result += item.toString() + comma;
}
result = result.substring(0, result.length() - 1);
return result;
}
Where is the problem?
I have trouble with this function because when I call a nested intersection in another one, this function never ends!
One example:
public static void main(String[] args) throws DLRException {
// TODO Auto-generated method stub
AtomicConcept atom = new AtomicConcept("one");
AtomicConcept at = new AtomicConcept("two");
List<Concept> list = new LinkedList<Concept>();
list.add(at);
list.add(atom);
DLRConceptIntersection intersection = new DLRConceptIntersection(list);
System.out.println(intersection); // works fine
list.add(intersection);
DLRConceptIntersection intersection2 = new DLRConceptIntersection(list);
System.out.println(intersection2); //loop never ends!
}
Is a correct approach to fix this problem?
You have a circular reference :
DLRConceptIntersection intersection = new DLRConceptIntersection(list);
list.add(intersection);
This causes the intersection's List to contain a reference to the same instance referred by intersection, which is why toString() run into infinite recursion.
I'm assuming you didn't intend intersection and intersection2 to share the same List.
You can avoid it if you create a copy of the List in the DLRConceptIntersection constructor:
public ConceptIntersection(List<Concept> l) throws Exception {
if(l.size()>1) {
this.list = new ArrayList<>(l);
} else {
throw new Exception("Intersection needs at least two concepts!");
}
}
This may come across as a relatively stupid question, but I'm getting tired of having to hard code statements such as:
private void doStuff(){
System.out.println(this.getClass().getName().toString()+ someText);{...};}
every time I want to
So I decided to implement an external method which writes in the output stream whenever I decide I need something written there such as:.
public static void println(Object obj, String s) {
System.out.println(obj.getClass().getName() + " > " + s);
}
So the question is, Is there a way to automatically set the value of the 's' variable in the method above to always default to "initialized" when writing source code (using TAB for code completion e.g. Netbeans)?
Many thanks in advance.
Use varargs as the second method parameter. This will also allow you to pass multiple debug statements.
public class Logger {
public static void main(String[] args) {
String test = "Test";
println(test);
println(test, "This is a test");
}
public static void println(Object obj, String...vargs) {
String defaultValue = "initialized";
if(vargs.length == 0){
System.out.println(obj.getClass().getName() + " > " + defaultValue);
}else{
for(String x: vargs){
System.out.println(obj.getClass().getName() + " > " + x);
}
}
}
}
Why don't you just overload the method with a default value?
public static void println(Object obj) {
println(obj, "Initalized");
}
public static void println(Object obj, String s) {
System.out.println(obj.getClass().getName() + " > " + s);
}
I have an enum with 4 values, and I have a method signature that accepts an enum value. I would like to be able to do something with all enum values not passed as the argument to doSomething().
public void doSomething(EnumThing thing){
EnumThing[] thingValues = EnumThing.values();
List<EnumThing> valuesNotPassedAsArg = new ArrayList<EnumThing>();
for(EnumThing th : thingValues){
valuesNotPassedAsArg.add(th);
}
valuesNotPassAsArg.remove(thing);
//here I would loop through all valuesNotPassAsArg and do something with them
}
public enum EnumThing{
SOMETHING, SOMETHINGELSE, ANOTHERTHING;
}
Is there a cleaner way to do this? I feel as if the loop to get the items from the thingValues array is superfluous.
Look into EnumSet. Specifically,
import java.util.EnumSet;
import static java.util.EnumSet.complementOf;
for (EnumThing t : complementOf(EnumSet.of(thing))) {
... do the work ...
}
#Marko's answer is better than this, but it might be helpful to know of this alternative way.
public static void main(String[] args) {
EnumThing thing = EnumThing.ANOTHERTHING;
List<EnumThing> list = new ArrayList<EnumThing>(Arrays.asList(EnumThing.values()));
list.remove(thing);
System.out.println(list);
}
public enum EnumThing{
SOMETHING, SOMETHINGELSE, ANOTHERTHING;
}
This prints out
[SOMETHING, SOMETHINGELSE]
Looking at your title, to iterate a range you do
for (int i = YourEnum.___RANGE___START___.ordinal() +1; i != YourEnum.__RANGE___END___.ordinal() ; i++) {
YourEnumvalue = YourEnum.values()[i];
//use value
}
or this
for (YourEnum value: EnumSet.range(YourEnum.___RANGE___START___, YourEnum.__RANGE___END___)) {
// use value
}
I you just want to skip a single element, then Skip Head's solution might outperform the complementOf, which seems to be an overkill in case of single iteration.
Another way is to use Stream.of method. For example:
public class EnumTest {
public static enum MyEnum {
VALUE1, VALUE2, VALUE3
}
public static void main(String[] args) {
Stream.of(MyEnum.values()).filter(v -> v != MyEnum.VALUE2).forEach(System.out::println);
}
}
Which prints:
VALUE1
VALUE3
public void doSomething(EnumThing thing){
EnumThing[] thingValues = EnumThing.values();
for(EnumThing th : thingValues){
if (th != thing) {
doSomethingElse(th);
}
}
}
Something like this is a little bit better I'd say
public void doSomething(EnumThing thing){
EnumThing[] thingValues = EnumThing.values();
List<EnumThing> valuesNotPassedAsArg = Arrays.asList(thingValues);
valuesNotPassAsArg.remove(thing);
//here I would loop through all valuesNotPassAsArg and do something with them
}
public enum EnumThing{
SOMETHING, SOMETHINGELSE, ANOTHERTHING;
}