isEven in another method - java

Something is very wrong here...
public class evenness {
public static Boolean isEven (Integer i) {
return (i % 2) == 0;
}
public static void main(String[] args) {
if (isEven(Integer i)) { //something wrong on this line.
System.out.print("YAY!");
}
}
}
Please help me sort it out!

You are supposed to give an Integer argument to the function isEven, for example 3 or 125.
I'm pretty sure that your IDE is telling you that it can't find the variable Integer. So you need to give a variable. The argument type is only required in the method definition.
For example:
int number = 4;
if(isEven(number)){
...
}
or more directly
if(isEven(4)){
...
}

Change
if (isEven(Integer i)) {
to something like
int i = 5;
if (isEven(i)) {
or
if (isEven(5)) {
You need to pass an integer to the method.

Just provide an argument where you call your method in main();
public class evenness {
public static Boolean isEven (Integer i) {
return (i % 2) == 0;
}
public static void main(String[] args) {
if (isEven(36)) { //something wrong on this line.
System.out.print("YAY!");
}
}
}

Following Java coding convention by changing the class name to Evenness.
public class Evenness
The method isEven(...) should accept int and return boolean. Both are primitive data types. This will make the program runs faster than using their wrappers. A wrapper is a reference type (object) that wraps a primitive type. For example, Integer wraps int and Boolean wraps boolean.
public static boolean isEven (int i) {
Send an argument to isEven(...)
if (isEven(2)) { // this line is now OK.

Related

Trying to print a method using another method

Not sure where I'm going wrong with this. I've asked someone in my class and they said there should be an argument with "toonRijSterren". when I do this I just get more errors, could someone have a look and tell me where I'm going wrong?
public static void main(String[] args) {
int aantal = 0;
toonRijSterren(aantal);
toonSterrenVierkant(aantal);
}
public static void toonRijSterren(int mpAantal) {
while (mpAantal < 6) {
System.out.print(" * ");
mpAantal++;
}
}
public static void toonSterrenVierkant(int mpAantal) {
for (int mpAatal = 0; mpAantal < 6; mpAantal++) {
System.out.println(toonRijSterren());
}
}
ther error line is in the brackets of the last toonRijSterren());
toonRijSterren is void method which means it does not return any value and therefore you can not put it inside System.out.println() or you can not assign it to some variable.
toonRijSterren expects an int argument which you have missed while calling it.
Given below is an example of how you should call toonRijSterren:
public static void toonSterrenVierkant(int mpAantal) {
for (int mpAatal = 0; mpAatal < 6; mpAatal++) {
toonRijSterren(mpAantal);
}
}
You are not passing the argument when you call your method.
Try this:
System.out.println(toonRijSterren(mpAatal));
First of all, your function toonRijSterren takes an int type parameter (according to its declaration), so you need to pass to it another argument. For example:
toonRijSterren(mpAantal)
Second, the function toonRijSterren returns void. That means, it just does an operation (in this case, printing) without returning anything. What you're trying to do is to use its return value (which doesn't exist) as an argument to System.out.println, which causes an error (because println expects an argument of some type).
You could achieve what I think you're trying to do with the line:
toonRijSterren(mpAantal);.
The function itself prints the values, so the println here is unnecessary and causes an error.
You are missing the parameter in your toonSterrenVierkant() function where you calling toonRijSterren.
Here is the corrected version of your code:
public static void toonSterrenVierkant(int mpAantal) {
for (; mpAantal < 6; mpAantal++) {
toonRijSterren(mpAatal);
}
}
As your methed toonSterrenVierkant(int mpAantal) has a int parameter, you must pass an int value as an argument in the last toonRijSterren(). For example, replace the line System.out.println(toonRijSterren()); with System.out.println(toonRijSterren(1));

Generic method with stack

my code:
public static void spilledOn (Stack<Object> st1,Stack<Object> st2){
while (!st2.isEmpty()){
st1.push(st2.pop());
}
}
public static int findLengthInStack (Stack<Object> st1){
Stack<Object> tmp=new Stack<>();
int count=0;
while (tmp.isEmpty()){
tmp.push(st1.pop());
count++;
}
toolsForAnything.spilledOn(st1, tmp);
return count;
}
when I call this method and I use another type of stack its not working well
(I mean I use Stack<Integer>)
Does anyone have any solution for this ?
(I hope its right that I use with object)
If you really wanted to use this algorithm for some reason, then for a general Stack you would need to declare a type parameter for each method.
// (Really an API would be using super and extends here,
// but let's keep it simple.)
public static <T> void spilledOn (Stack<T> st1,Stack<T> st2){
// ^^^ ^ ^
[...]
// (I'm using a different name (E vs T) here
// just to illustrate that I am declaring two variables.
// Using the same letter would be more conventional.)
public static <E> int findLengthInStack (Stack<E> st1){
// ^^^ ^
Stack<E> tmp=new Stack<>();
// ^
If you want to write the (unnecessary) method to find how many elements are in the stack, you can do it like this:
public class Helper {
private static <T> int findSize(Stack<T> input) {
return input.size();
}
public static void main(String[] args) {
Stack<Integer> stack = new Stack<>();
stack.push(4);
stack.push(9);
System.out.println(findSize(stack));
}
}
Why I said unnecessary? Because you can simply write:
System.out.println(stack.size());
instead of:
System.out.println(findSize(stack));

Does java have some convention to indicate that object is in empty state?

Of course, empty definition can differ. I'm used to PHP's empty though, which calls empty everything that evaluates to false. I'd like to call these things empty in my Java application:
null
String of zero length
0 Integer, Float or Double
false
Any array of zero length
Empty ArrayList or HashMap
Java has, for example, toString convention. Every object is granted to give you some string representation. In my Settings class I operate with HashMap<String, Object>. My empty method looks now like this:
public boolean empty(String name) {
Object val = settings.get(name);
if(val!=null) {
return false;
}
return true;
}
I'd like to extend it in a conventional manner, rather than if(val instanceof XXX) chain.
No, there is no standard convention for this in Java. Also, in Java there is no such thing as "evaluate to false" (except for booleans and Booleans, of course).
You will have to write a method (or rather, a series of overloaded methods for each type you need it for) which implements your notion of "empty". For example:
public static boolean isEmpty(String s) {
return (s == null) || (s.isEmpty());
}
public static boolean isEmpty(int i) {
return i == 0;
}
...
You could use overloading to describe all the "empty" objects:
public static boolean empty(Object o) {
return o == null;
}
public static boolean empty(Object[] array) {
return array == null || array.length == 0;
}
public static boolean empty(int[] array) { //do the same for other primitives
return array == null || array.length == 0;
}
public static boolean empty(String s) {
return s == null || s.isEmpty();
}
public static boolean empty(Number n) {
return n == null || n.doubleValue() == 0;
}
public static boolean empty(Collection<?> c) {
return c == null || c.isEmpty();
}
public static boolean empty(Map<?, ?> m) {
return m == null || m.isEmpty();
}
Examples:
public static void main(String[] args) {
Object o = null;
System.out.println(empty(o));
System.out.println(empty(""));
System.out.println(empty("as"));
System.out.println(empty(new int[0]));
System.out.println(empty(new int[] { 1, 2}));
System.out.println(empty(Collections.emptyList()));
System.out.println(empty(Arrays.asList("s")));
System.out.println(empty(0));
System.out.println(empty(1));
}
AFAIK there is no such convention. It's fairly common to see project specific utility classes with methods such as:
public static boolean isEmpty(String s) {
return s == null || s.isEmpty();
}
However I personally think its use is a bit of a code smell in Java. There's a lot of badly written Java around, but well written Java shouldn't need null checks everywhere, and you should know enough about the type of an object to apply type-specific definitions of "empty".
The exception would be if you were doing reflection-oriented code that worked with Object variables who's type you don't know at compile time. That code should be so isolated that it's not appropriate to have a util method to support it.
Python's duck-typing means the rules are sort of different.
How about creating an interface EmptinessComparable or something similar, and having all your classes implement that? So you can just expect that, and not have to ask instanceof every time.
Java does not, but Groovy does. Groovy runs on the Java VM alongside Java code and provides many shortcuts and convenient conventions such as this. A good approach is write foundation and crital project components in Java and use Groovy for less critical higher level components.
If you want to use the one approach, I would overload a utility method:
public class MyUtils {
public static boolean isEmpty(String s) {
return s == null || s.isEmpty();
}
public static boolean isEmpty(Boolean b) {
return b == null || !b;
}
// add other versions of the method for other types
}
Then your code always looks like:
if (MyUtils.isEmpty(something))
If the type you're checking isn't supported, you'll get a compiler error, and you can implement another version as you like.
There are ways to establish the notion of emptiness but it's not standardized across all Java classes. For example, the Map (implementation) provides the Map#containsKey() method to check if a key exists or not. The List and String (implementations) provide the isEmpty() method but the List or String reference itself could be null and hence you cannot avoid a null check there.
You could however come up with a utility class of your own that takes an Object and using instanceof adapts the empty checks accordingly.
public final class DataUtils {
public static boolean isEmpty(Object data) {
if (data == null) {
return false;
}
if (data instanceof String) {
return ((String) data).isEmpty();
}
if (data instanceof Collection) {
return ((Collection) data).isEmpty();
}
}
}
The Guava Libraries already contains Defaults class that do just that.
Calling defaultValue will return the default value for any primitive type (as specified by the JLS), and null for any other type.
You can use it like shown below:
import com.google.common.base.Defaults;
Defaults.defaultValue(Integer.TYPE); //will return 0
Below is example code on how to use it:
import com.google.common.base.Defaults;
public class CheckingFieldsDefault
{
public static class MyClass {
private int x;
private int y = 2;
}
public static void main() {
MyClass my = new MyClass();
System.out.println("x is defualt: " + (my.x == Defaults.defaultValue(box(my.x).TYPE)));
System.out.println("y is defualt: " + (my.y == Defaults.defaultValue(box(my.y).TYPE)));
}
private static <T extends Object> T box(T t) {
return t;
}
}

Reference a method within a method in java?

Ok, so I am going to see if this makes sense. In the second method below (int numAdd) I want to be used for the private method (int searchingNum). I don't really understand how private methods work, but whatever number the user enters for the (int numAdd) I want to be duplicated for the parameters in the first method. How is this possible?
//See if user input returns -1 to test whether or not number exists in the array
private int indexOf(int searchingNum)
{
}
//Add number in the array
public boolean addNumber(int numAdd)
{
if (list.contains(numAdd))
{
return false;
}
else
{
list.add(numAdd);
count++;
return true;
}
}
that's it? indexOf(numAdd);
public boolean addNumber(int numAdd)
{
// somewhere, in the middle of nowhere
indexOf(numAdd);
// more of code
}
You can call method of same class directly. No need to do anything. Like this :
public boolean addNumber(int numAdd)
{
int abc = indexOf(numAdd);
//Whatever you want to do...
}

accessing elements of an array which has been passed as a parameter - Java

I have a method which takes an array as a parameter from another class:
public void memPass(Memory[] memLocList) {
memList = memLocList;
for (int i = 0; i < 10; i++) {
System.out.println(memList[i].getSomething());
}
}
-EDIT-
The above prints out 10 values (integers) but if I try the same in the other method with an integer between 0 & 10 I get an NPE.
Can anyone tell me how to access the elements of this array from another method, which also takes in a parameter from another class?
I'm trying to do something along these lines:
public void accessArray(int mem) {
int someInt = memList[mem].getSomething();
}
-EDIT- Sorry, I should add that this gives a NullPointerException.
-NEW EDIT-
OK, I've now edited the code so that all I have in the class is:
public class PLoop {
// instance variable
public Memory[] memlist;
// method 1
public void memPass(Memory[] memLocList) {
memList = memLocList;
System.out.println(memList.length);
}
// method 2
public void accessArray(int mem) {
System.out.println(memList.length);
}
}
The first method prints an integer representing the length of "memList" and the second gives an NPE.
If I'm understanding you right, you want to be able to store memLocList then access it later? If so, I can't see what creating an instance variable wouldn't work.
public class Test {
public Memory[] memlist;
public void memPass(Memory[] memLocList) {
memList = memLocList;
}
public void accessArray(int mem) {
int someInt = memList[mem].getSomething();
}
}
Of course, I don't work in Java enough any more, so it might not be possible to create and assign an instance variable like that. But you could always store the elements in another container.
public class Test {
public List<Memory> memlist;
public void memPass(Memory[] memLocList) {
memlist = new ArrayList<Memory>(Arrays.asList(memLocList));
}
public void accessArray(int mem) {
int someInt = memList.get(mem).getSomething();
}
}
Sorry if I have any syntax errors. But you get the main idea.
If memList is an instance variable of that class and this is the same class in both situations (both methods) then this is obviously a null value at some index of memList.
private static class Memory {
private static int index = 0;
public int getSomething() {
return index++;
}
}
private static class Test {
public Memory[] memlist;
public void memPass(Memory[] memLocList) {
memlist = memLocList;
}
public void accessArray(int mem) {
int someInt = memlist[mem].getSomething();
System.out.println(someInt);
}
}
public static void main(String args[]) {
Test t = new Test();
Memory[] memList = new Memory[4];
memList[0] = new Memory();
memList[1] = null;
t.memPass(memList);
t.accessArray(0);
t.accessArray(0);
t.accessArray(1); //NPE thrown because null value in array
//or
Test t2 = new Test();
t2.accessArray(0); //NPE thrown because array is null (different instance)
}
In your implementation, you are already assuming that the array being passed to the method has 10 elements and that each of these array items has a value, hence, at some point you encounter a NullPointerException. This is dangerous especially when you are just processing an array that is passed as an argument to the method. To ensure that you are only accessing the elements that are available in the array, you need to check what the length of the array is. Also, you need to ensure that whenever you call the methods of an element in an array, (or do anything with it), check first whether it is actually there. For your for loop, you can do something like this:
if (memList != null) {
for (int i = 0; i < memList.length; i++) {
if (memList[i] != null) {
System.out.println(memList[i].getSomething());
}
}
}
That way it is safe from nullpointer exceptions. Using the same concept, you can also apply it to your method like this:
public void accessArray(int mem) {
if (mem > -1 && memList != null && memList.length > mem && memList[mem] != null){
int someInt = memList[mem].getSomething();
}
}
Of course this is assuming that the method with the for loop and the accessArray method are in the same class (or parent-child class) and memList is an instance variable.
And to save the elements of the array as a deep copy of memLocList, you can use what #GJK has suggested which is Arrays.asList to an instance variable and apply the same concept of nullpointer checking that I mentioned above.

Categories

Resources