From a book I'm going through:
"Design a class name MyInteger. The class contains:
...blah, blah, blah...
The methods isEven(), isOdd(), and isPrime() that return true if the value in this object is even, odd, or prime, respectively.
The static methods isEven(int), isOdd(int), and isPrime(int) that return true if the specified value is even, odd, or prime, respectively.
The static methods isEven(MyInteger), isOdd(MyInteger), isPrime(MyInteger), that return true if the specified value is even, odd, or prime, respectively."
Here's what I've got so far. The top is easy to implement with object.isEven()...
The second, I assume this is just to display results without actually setting the value and changing the object? So I could just do object.isEven(2)?
The last one... that's throwing me off a lot. I have no idea. =/ Please help me out. Thanks in advance.
To clarify:
1.
public boolean isEven(){
// code
}
MyInteger object = new MyIntger(50);
object.isEven();
2.
public boolean isEven(int num){
// code
}
MyInteger.isEven(50)???
3.
public boolean isEven(int MyInteger)???
???
class MyInteger {
int number;
// CONSTRUCTOR
public MyInteger(int a) {
number = a;
}
public int getNumber() {
return number;
}
static boolean isEven(MyInteger myint) {
if (myint.getNumber() % 2 == 0)
return true;
else
return false;
}
}
Now the main class:
public class MainClass {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MyInteger myInteger=new MyInteger(10);
boolean result=MyInteger.isEven(myInteger);
if(result==true)
System.out.println("true result");
else
System.out.println("false result");
}
}
This seems to be the one that's confusing
boolean odd2 = MyInteger.isOdd(new MyInteger(5)); // static call
You use use an instance of MyInteger to pass as an argument. Another way to pass MyInteger as an argument is:
MyInteger num = new MyInteger(5);
boolean odd2 = MyInteger.isOdd(num); // static call
class MyInteger{
int num;
public MyIntger(int num){
this.num = num;
}
// Method 1
public static boolean isOdd(int num){
...
}
// Method 2
public boolean isOdd(){
...
}
// Method 3
public static boolean isOdd(MyInteger num){
...
}
}
public class TestMyInteger{
public static void main(String[] args){
// Method 1 call
boolean odd1 = MyIntger.isOdd(5); // static call
// Method 3 call
boolean odd2 = MyInteger.isOdd(new MyInteger(5)); // static call
// Method 2 call
MyIntger num = new MyIntger(5); // create instance
boolean odd3 = num.isOdd(); // instance call
System.out.println(odd1);
System.out.println(odd2);
System.out.println(odd3);
}
}
For second one, the method is belong to the class. But not the created object.
If Your code like this :
MyInteger myInteger = new MyInteger(100);
You can call the method by this
MyInteger.isEven(50);
or
myInteger.isEven(50);
It is not related to 100 which set in object.
Consider this as a pointer, and then you might want to look at this question.
public class MyInteger {
private int value;
public MyInteger(int value) {
super();
this.value = value;
}
public static boolean isPrime(int value) {
// I would increment counter then test if the result of value modulo counter
// (that is if value % counter != 0) until counter >= square_root(value).
// Then the value is prime, otherwise
return false;
}
public static boolean isEven(int value) {
return (value & 1) == 0;
}
public static boolean isEven(MyInteger m) {
return isEven(m.value);
}
public static boolean isPrime(MyInteger m) {
return isPrime(m.value);
}
public static boolean isOdd(int value) {
return !isEven(value);
}
public static boolean isOdd(MyInteger m) {
return isOdd(m.value);
}
public boolean isEven() {
return isEven(this.value);
}
public boolean isOdd() {
return isOdd(this.value);
}
public boolean isPrime() {
return isPrime(value);
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
You would be performing actions upon the MyInteger object rather than just a straight int.
Let's say your private variables and constructor look like this (we don't know exactly because it isn't posted):
private int myInt;
public MyInteger(int thisInt) {
myInt = thisInt;
}
You will need to implement an accessor method that returns the value of myInt within an instance of the MyInteger class and then use this accessor method in your static method to perform the operation.
So as an accessor method:
public int getInt()
{
return myInt;
}
And then your static method would reference this method in the same way you would in another program. Note that you have to specify the use of the MyInteger object even within the class:
public static boolean isEven(MyInteger myInteger)
{
//Code here
}
In terms of calling the static method, it would look something like this:
MyInteger myInteger = new MyInteger(50);
MyInteger.isEven(myInteger);
Here, you are referencing an instance of the MyInteger object (myInteger) rather than the primitive int, but because isEven isn't directly connected to a specific object, you have to tell your code where to find the isEven() method, the MyInteger class.
Related
Why is the reference variable ‚Input inside‘ necessary?
How does the ‚Input inside‘ work here?
What does the code: The code adds 5 to the x-value (in this case 4) and uses the square of the new value. So (4+5)^2.
Thank you. 😀
Code:
abstract class Input {
protected Input inside;
public Input() {
}
public Input(Input inside) {
this.inside = inside;
}
public int calculate(int value) {
if(inside == null) {
return value;
}
return inside.calculate(value);
}
public static void main(String[] args) {
Input chaincalculate = new Square(new AddFive());
int x;
x = 4;
System.out.println("The value is: " + (int) chaincalculate.calculate(x));
}
}
class AddFive extends Input {
public AddFive() {
}
public AddFive(Input inside) {
super(inside);
}
public int calculate(int value) {
value = super.calculate(value);
return value+5;
}
}
class Square extends Input {
public Square() {
}
public Square(Input inside) {
super(inside);
}
public int calculate(int value) {
value = super.calculate(value);
return value * value;
}
}
}
All the classes extending the abstract class Input, have their own calculate methods, and since, these classes, would want to use the abstract class Calculate method, the reference variable input inside is necessary to invoke/reference the calculate method residing in Input abstract class, to support the method chaining implemented in the code
Let's say, 5 is considered a good number. A method is to define to check a number is good or not. Parameter type int and return type is boolean. If argument is 5 it will return true and false otherwise.
See this code:
class Library{
boolean isGood(int num){
return num==5;
}
}
public class String_handling {
public static void main(String[] args) {
int num=8;
System.out.println(new Library().isGood(num));
}
}
I know this code is okay.
But I want to define a method such that I can invoke in this way:
System.out.println(num.isGood());
As work on string like this:
MyString.contains("xy");
MyString.substring(0,4);
Is there any way? Give an example.
Since int is a primitive, the only way you can to that, is to make your own class MyInteger and add your method isGood(), like so
public class MyInteger{
private int num;
public MyInteger(int num){
this.num = num;
}
public boolean isGood(int num){
return this.num == num;
}
}
I have this enum:
public enum Digits {
ZERO(0);
private final int number;
private Digits(int number) {
this.number = number;
}
public int getValue(){
return number;
}
}
And I would like to make setter in another class which can me offer following feature:
- I will give it integer value (in this case, 0) and that setter will set enum ZERO to my local variable of type Digits
Is that possible?
Many thanks!
It is possible, but not by invoking the enum's constructor, as it's available only within the enum itself.
What you can do is add a static method in your enum that retrieves the correct instance based on a given value, e.g. ZERO if the given value is 0.
Then you'd invoke that method in your other class when given the int argument.
Self contained example
public class Main {
static enum Numbers {
// various instances associated with integers or not
ZERO(0),ONE(1),FORTY_TWO(42), DEFAULT;
// int value
private int value;
// empty constructor for default value
Numbers() {}
// constructor with value
Numbers(int value) {
this.value = value;
}
// getter for value
public int getValue() {
return value;
}
// utility method to retrieve instance by int value
public static Numbers forValue(int value) {
// iterating values
for (Numbers n: values()) {
// matches argument
if (n.getValue() == value) return n;
}
// no match, returning DEFAULT
return DEFAULT;
}
}
public static void main(String[] args) throws Exception {
System.out.println(Numbers.forValue(42));
System.out.println(Numbers.forValue(10));
}
}
Output
FORTY_TWO
DEFAULT
You can do it like this:
private Digits digit;
public void setDigit(int number) {
for (Digits value : Digits.values()) {
if(value.getValue() == number) {
digit = value;
}
}
}
Here is the example how to achieve what you want
public enum Digit {
ONE(1),
TWO(2),
THREE(3);
private static final Map<Integer, Digit> mappingMap = new HashMap<Integer, Digit>();
static {
for (Digit m : Digit.values()) {
mappingMap.put(m.getValue(), m);
}
}
private final int digit;
Digit(int aDigit) {
digit = aDigit;
}
public int getValue() {
return digit;
}
public static Digit getByDigit(int aDigit) {
return mappingMap.get(aDigit);
}
}
This approach has better performance than iterating over all constants for large enums.
Is there a "typeof" like function in Java that returns the type of a primitive data type (PDT) variable or an expression of operands PDTs?
instanceof seems to work for class types only.
Try the following:
int i = 20;
float f = 20.2f;
System.out.println(((Object)i).getClass().getName());
System.out.println(((Object)f).getClass().getName());
It will print:
java.lang.Integer
java.lang.Float
As for instanceof, you could use its dynamic counterpart Class#isInstance:
Integer.class.isInstance(20); // true
Integer.class.isInstance(20f); // false
Integer.class.isInstance("s"); // false
There's an easy way that doesn't necessitate the implicit boxing, so you won't get confused between primitives and their wrappers. You can't use isInstance for primitive types -- e.g. calling Integer.TYPE.isInstance(5) (Integer.TYPE is equivalent to int.class) will return false as 5 is autoboxed into an Integer before hand.
The easiest way to get what you want (note - it's technically done at compile-time for primitives, but it still requires evaluation of the argument) is via overloading. See my ideone paste.
...
public static Class<Integer> typeof(final int expr) {
return Integer.TYPE;
}
public static Class<Long> typeof(final long expr) {
return Long.TYPE;
}
...
This can be used as follows, for example:
System.out.println(typeof(500 * 3 - 2)); /* int */
System.out.println(typeof(50 % 3L)); /* long */
This relies on the compiler's ability to determine the type of the expression and pick the right overload.
You can use the following class.
class TypeResolver
{
public static String Long = "long";
public static String Int = "int";
public static String Float = "float";
public static String Double = "double";
public static String Char = "char";
public static String Boolean = "boolean";
public static String Short = "short";
public static String Byte = "byte";
public static void main(String[] args)
{
//all true
TypeResolver resolver = new TypeResolver();
System.out.println(resolver.getType(1) == TypeResolver.Int);
System.out.println(resolver.getType(1f) == TypeResolver.Float);
System.out.println(resolver.getType(1.0) == TypeResolver.Double);
System.out.println(resolver.getType('a') == TypeResolver.Char);
System.out.println(resolver.getType((short) 1) == TypeResolver.Short);
System.out.println(resolver.getType((long) 1000) == TypeResolver.Long);
System.out.println(resolver.getType(false) == TypeResolver.Boolean);
System.out.println(resolver.getType((byte) 2) == TypeResolver.Byte);
}
public String getType(int x)
{
return TypeResolver.Int;
}
public String getType(byte x)
{
return TypeResolver.Byte;
}
public String getType(float x)
{
return TypeResolver.Float;
}
public String getType(double x)
{
return TypeResolver.Double;
}
public String getType(boolean x)
{
return TypeResolver.Boolean;
}
public String getType(short x)
{
return TypeResolver.Short;
}
public String getType(long x)
{
return TypeResolver.Long;
}
public String getType(char x)
{
return TypeResolver.Char;
}
}
There are two ways that you can use to determine the type of the Primitive type.
package com.company;
public class Testing {
public static void main(String[] args) {
int x;
x=0;
// the first method
System.out.println(((Object)x).getClass().getName());
if (((Object)x).getClass().getName()=="java.lang.Integer")
System.out.println("i am int");
// the second method it will either return true or false
System.out.println(Integer.class.isInstance(x));
}
}
I'm just beginning in programming and I'd like to make exercise from a book, but I can't. That's my problem:
public class increment {
int increment() {
return this + 1; // aka this++
}
public static void main(String[] args) {
int a = 0;
System.out.println(a.increment());
}
}
As you for sure guessed already, that it doesn't works, I want to ask you how to get outputed integer a incremented by one, but using keyword 'this'.
Regards and sorry for stupid questions.
It is strange to name a class like a method.
I guess you wanted this:
public class Counter {
int val;
public Counter (int start) {
val = start;
}
public void increment() {
val ++;
}
public String toString () {
return Integer.toString (val);
}
public static void main(String[] args) {
Counter counter = new Counter (0);
counter.increment ();
System.out.println(counter.toString ());
}
}
this is an object (the current object). You cannot "increment" it.
A way to do it is:
public class Increment {
int a = 0;
int increment() {
return a + 1;
// or: return this.a + 1;
// or: a++; return a; if you want a to be incremented from now on
}
public static void main(String[] args) {
Increment inc = new Increment();
System.out.println(inc.increment());
}
}
The this keyword in Java refers to the current scope's object instance. I don't think it's what you're looking for in this case.
In your example, a isn't an object of the class increment, it is a primitive int. In order to use the .increment() function you defined, it would have to be an object of type increment.
One option that may be what you're looking for would be the following.
public class Increment { //Java likes capitalized class names
private int myInt;
public Increment(int a) { //constructor
myInt = a;
}
public int increment() {
return ++myInt;
}
public static void main(String[] args) {
Increment a = new Increment(0);
System.out.println(a.increment());
}
}
In this example, we make a new class of type increment, which internally contains an integer. Its increment method increments that internal integer, and then returns the number.
you are using operator + for your current object (this). Operator overloading is not supported in java.
Something like this will work:
class MyInteger {
private int internal;
public MyInteger( int value ){
this.internal = value;
}
public int incerment(){
return ++this.internal;
}
}
public class Increment {
public static void main(String[] args) {
MyInteger a = new MyInteger(0);
System.out.println(a.increment());
}
}
You see, you can only implement methods for your own classes, not for existing classes, or for primitives like int.
i don't think you can use this to return the value, except if you're making a new class like this:
class Increment1
{
private int a;
public int increment2(int a)
{
this.a=a;
return this.a + 1;
}
}
public class Increment
{
static Increment1 b = new Increment1();
public static void main(String[] args)
{
int a = 0;
System.out.println(b.increment2(a));
}
}
You cannot increment a class like this.
You have to use a member variable that you can increment.
public class Test {
private int var;
public Test(int i) {
this.var = i;
}
int increment() {
this.var++;
}
}
public static void main(String[] args) {
Test t = new Test(0);
System.out.println(t.increment());
}
This refers to the current instance of the class, not a particular member.
You want to increment a property (I'm guessing of type long or int), and not the instance of your increment class (should be Increment, by the way).
Something like this would work:
public class increment {
private int innerValue = 0;
int increment() {
innerValue+=1
return innerValue; // aka this++
}
public static void main(String[] args) {
increment a = new increment()
System.out.println(a.increment());
}
}