I have a code
public int getValue()
{
int i = null;
if(condition)
{
i = 10;
}
return i;
}
This works fine for String variables. How to do the same with int variables ?
int is a primitive type. It cannot hold null value.
You can either use Integer to hold null values, or use 0 (or -1) as the default int value.
null is a valid value for objects, not for primitives.
Since String instances are objects, this is why it compiles it this case.
To get your code compiling in the case with the int, just do:
int i;
if (condition) {
i = 10;
} else {
i = -1; //or some other value when the condition is not met.
}
Only Objects can hold a null value. Since int is a primitive type it has its own default value.
Objects default is null
Data Type Default Value (for fields)
byte 0
short 0
**int** 0
long 0L
float 0.0f
double 0.0d
char '\u0000'
**String (or any object)** null
boolean false
Try
int i = 0;
or even left it and assign later, If it is a instance member. Remember that local variables need to be initialize before they are using at that place you have to assign.
The nullequivalent for int is 0.
You can't put "null" as a value for primitive data type in java, but you can use Objects like "Integer":
Example:
public Integer getValue() {
Integer i;
return i = (condition ? null : 10);
}
The previous code will return null as Integer object if your condition is true, otherwise it will return 10.
But, commonly used to return -1 as default int value if conditions not matched, so you can use:
public int getValue() {
int i = -1;
return i = (condition ? -1 : 10);
}
You can use Integer instead of int .
public static Integer getValue()
{
Integer i = null;
if(condition)
{
i = 10;
}
return (i==null)?0:i;
}
If you don't want to change int , then you can give
public static int getValue()
{
int i=0;
if(condition)
{
i = 10;
}
return i;
}
I use a sentinel value like MIN_VALUE
public int getValue() {
int i = Integer.MIN_VALUE;
// do something
if (i == Integer.MIN_VALUE) {
i = 10;
}
return i;
}
However the simpler solution is to give an appropriate default value like 10
public int getValue() {
int i = 10;
// do something
return i;
}
Primitives (int, long, byte, etc) doesn't have null values, that applies only to objects (and String is an object in Java). Also note that default value for primitives is usually 0, for objects is null. You have several options to overcome this
Throw an exception
public int getValue() {
if(condition) {
return 10;
}
throw new IllegalStateException("Condition must be met");
}
Or you can return some arbitrary number which will tell you that condition wasn't met, -1 is a standard way.
public int getValue() {
int value = -1;
if(condition) {
value = 10;
}
return value;
}
Also note that i is usually used within for loop, so I would prefer different name for that variable, it can be confusing otherwise.
Related
I am new to Java and I am trying to write a class with constructors and methods that adds and divides two numbers, and also compares if one object is larger or equal than the other. But I am getting an error: The method plus(int) in the type Compare is not applicable for the arguments (Compare). what's wrong?
Here's the code:
public class Compare {
// fields
private int number;
private int plus;
private double div;
// constructor
public Compare (int n) {
number = n;
}
public int plus (int x) {
return this.number + x;
}
public int div (int x) {
return this.number / x;
}
public boolean isLargerThan (int x) {
return this.number > x;
}
public boolean isEqualTo (int x) {
return this.number == x;
}
public static void main(String[] args) {
Compare n1 = new Compare(9);
Compare n2 = new Compare(4);
Compare sum = n1.plus(n2);
Compare div = n1.div(n2);
boolean check1 = sum.isLargerThan(n1);
boolean check2 = div.isLargerThan(n2);
boolean check3 = div.isEqualto(sum);
}
}
The requirement is to create sum and div objects using Compare constructor that will be equal to n1 plus n2, with plus method or division as applicable.
It may be that here you want a new Compare, containing the sum.
public Compare plus (int x) {
return new Compare(number + x);
}
public Compare plus (Compare x) {
return new Compare(number + x.number);
}
This also is implied by expecting a Compare object, not an int as shown.
With that Compare would become immutable, which is very good, as you then can share objects in different variables without problems (changing one variable's value changing other variables' values).
#Override
public String toString() {
return Integer.toString(number);
}
public int intValue() {
return number;
}
The issue here is for the "plus", "div", "isLargerThan" and "isEqualTo" methods in "Compare" class the argument/return type is of type "int". But in "main" function you are passing the object and expecting object of type "Compare".
To fix it either change the argument/return type to "Compare" for those methods in "Compare" class or pass the "int" value as parameter and get "int" value in "main" function.
The plus and div methods take an int and return an int and you are trying to receive their output in a Compare object. Also, isLargerThan takes an int and not a Compare.
Problem is here :
Compare sum = n1.plus(n2);
Compare div = n1.div(n2);
methods : plus and div return int value not an objet of Class Compare.
public int plus (int x) {
return this.number + x;
}
public int div (int x) {
return this.number / x;
}
Add getter method in Compare Class.
public int getNumber(){
return number;
}
Use below code and try to run:
public static void main(String[] args) {
Compare sum = new Compare(9);
Compare divObj = new Compare(4);
sum.plus(n2);
divObj.div(n2);
boolean check1 = sum.isLargerThan(sum.getNumber());
boolean check2 = divObj.isLargerThan(divObj.getNumber());
boolean check3 = divObj.isEqualto(sum.getNiumber());
}
I'm getting the error: incompatible types: boolean cannot be converted to int error while compiling the android app in Android Studio. The problem is in only one method.
private static int get_wx_inx(String str) {
boolean equalsIgnoreCase = str.equalsIgnoreCase("木");
int equalsIgnoreCase2 = str.equalsIgnoreCase("火");
if (str.equalsIgnoreCase("土")) {
equalsIgnoreCase2 = true;
}
if (str.equalsIgnoreCase("金")) {
equalsIgnoreCase2 = 3;
}
return str.equalsIgnoreCase("水") ? 4 : equalsIgnoreCase2;
}
I don't know what could be wrong. Can you help me to figure out the problem. Thanks in advance.
Your question is not bit clear but you might want this:
private static int get_wx_inx(String str) {
if(str.equalsIgnoreCase("木")) {
return 0;
} else if(str.equalsIgnoreCase("火")) {
return 1;
}else if(str.equalsIgnoreCase("土")) {
return 2;
} else if(str.equalsIgnoreCase("金")) {
return 3;
} else if(str.equalsIgnoreCase("水")) {
return 4;
} else {
return 0;// write default return here. If every condition goes false then this default will be return.
}
}
You can make use of Strings in switch statements and return respective int values.
https://docs.oracle.com/javase/7/docs/technotes/guides/language/strings-switch.html
As we can't have mixed type for return value. You can consider 0(FALSE) and 1(TRUE). Or any such random value.
Problem lies in this statement:
int equalsIgnoreCase2 = str.equalsIgnoreCase("火");
equalsIgnoreCase() method returns a boolean value and you are assigning it to an int value. That's why it is giving this error.
Java is not a C language, so booleans cannot be integers, they are totally different types and cannot be mixed. In the 3rd line you are assigning boolean value to an int
I'm trying to check if a number is a square, and if a number is triangular.
The issue is happening at sqrt(num) which is returning 0 for all numbers I test.
I'm using an online compiler, tried several compilers, so it's not a compiling issue. Tried to declare num as a double and as an int, same results.
I'm new to Java, but not new to programming, I searched online, checked my code several times, everything looks fine, it even worked as expected before adding the variables for checking triangular number, but after declaring the variables checkTri and checkTriSqr, this started to happen. I'm sure this have nothing to do with declaring these variables (almost sure), could anyone please help me understand what's going on here?
import static java.lang.Math.sqrt;
import static java.lang.Math.round;
public class Parent{
public static void main(String[] args){
class Number
{
public int num ;
double numSqr = sqrt(num );
double roundNumSqr = round(numSqr) ;
double checkTri = 8 * num + 1 ;
double checkTriSqr = sqrt(checkTri) ;
public void prinTest()
{
System.out.println(num);
System.out.println(numSqr);
System.out.println(roundNumSqr);
System.out.println(checkTri);
System.out.println(checkTriSqr);
}
public boolean isSqr()
{
if (numSqr == roundNumSqr)
{
return true;
}
else
{
return false;
}
}
public boolean isTriangular(){
if (checkTriSqr * checkTriSqr == checkTri )
{
return true;
}
else
{
return false;
}
}
}
Number number = new Number();
number.num = 350;
number.prinTest();
System.out.println(number.isSqr());
System.out.println(number.isTriangular());
}
}
EDIT: The following screen shot is from the tutorial I'm following, concerning declaring classes within methods!
This:
public int num ;
double numSqr = sqrt(num );
initialises num to 0 upon instance construction (the default value for an integer in the absence of assignment), and numSqr is set immediately afterwards (to zero).
You need to recalculate the sqrt() each time you subsequntly set num (perhaps by providing a method setNum() and recalculating everything within that method)
I wouldn't call your class Number, btw. There's already a Number class in the standard Java class set.
numSqr is created in the constructor, whereas number.num = 350;is declared after the construction of your object.
You can use a constructor like this :
public Numer(int num){
this.num=num;
this.numSqr=sqrt(num)
//.... ... ...
}
You can also use an empty constructor and a setter to set the number attribute :
public void setNumber(int num){
this.num=num;
this.numSqr=sqrt(num)
//.... ... ...
}
The values numSqr, roundNumSqr, etc, are all set at the point of the object's creation, however you don't set num to anything until after the object is created. The result is that, for instance,
At creation:
num = 0
therefore
numSqr = 0
roundNumSqr = 0
etc
Then, you set num = 350
But you don't reset the values of numSqr, etc, so this is still the case:
numSqr = 0
roundNumSqr = 0
You need to make a constructor for this class that takes in the value of num and then sets all of the corresponding values, so that they're only set after num has been set (or, add a "calculate" function that updates all the values).
You can modify in this way and compare with technology you have worked on .
import static java.lang.Math.sqrt;
import static java.lang.Math.round;
public class Number {
public int num = 0;
public void prinTest() {
System.out.println(this.num);
System.out.println(this.getSqrt(this.num));
System.out.println(this.getCheckTri());
}
private double getSqrt(double value) {
return sqrt(value);
}
public boolean isSqr() {
if (this.getSqrt(this.num) == round(this.getSqrt(this.num))) {
return true;
} else {
return false;
}
}
private double getCheckTri() {
return 8 * this.num + 1;
}
public boolean isTriangular() {
if (this.getSqrt(this.getCheckTri()) * this.getSqrt(this.getCheckTri()) == this.getCheckTri()) {
return true;
} else {
return false;
}
}
public static void main(String[] args) {
Number number = new Number();
number.num = 49;
number.prinTest();
System.out.println(number.isSqr());
System.out.println(number.isTriangular());
}
}
You should read some basic tutorials as you have added class inside main method,which means you need more time to check out the syntax.
The other answers alreade said, that the field num was not set to the input number, and that the other fields were actually evaluated on object creation, and hence zero too.
The purpose however is achieved by simple functions:
public static boolean isSquare(int num) {
int root = (int) Math.round(Math.sqrt(num));
return root*root == num;
}
public static boolean isCubic(int num) {
int root = (int) Math.round(Math.cbrt(num));
return root*root*root == num;
}
This exploits the cubic root.
As a comparison of doubles, a sqrt result and its rounded long value are still imprecise, I prefer to recalculate the original parameter.
public int num ;
double numSqr = sqrt(num);
By default, declared instance integer variables (variables declared inside class body) are initialized with 0 (zero). Hence, your code does nothing but take a square root of zero, which is zero.
class DirectMappedCache extends Cache {
private int logLineSize; //log_2 of the number of bytes per cache line
private int logNumLines; //log_2 of the number of cache lines
private TreeMap<String, CacheSlot> tmap;
public DirectMappedCache(int logLineSize, int logNumLines) {
//constructor that takes lengths of different fields
this.logLineSize = logLineSize;
this.logNumLines = logNumLines;
tmap = new TreeMap<String, CacheSlot>();
}
public boolean read(String addr) {
System.out.println("Read from address " + addr + ": ");
String tag = addr.substring(0,9);
String slotnumber = addr.substring(9,13);
String offset = addr.substring(13,16);
if(tmap.containsKey(slotnumber)){
CacheSlot temp = tmap.get(slotnumber);
if(temp.valid){
if(tag.equals(temp.tag)){
return true;
}
}
}
CacheSlot put = new CacheSlot();
put.valid = true;
put.tag = tag;
tmap.put(slotnumber, put);
return false;
}
public int numHits(){
int HitCounter = 0;
if(read(addr)){
return HitCounter++;
}
return 0;
}
}
I am making a Cache Simulator but I don't think my numHits() is working because the way I'm calling the value is wrong.
The problem is not the way you call the read() method. Your numHits() method always returns 0 because you return the value of a local variable, which is always initialized to 0.
numHits() would only make sense if HitCounter becomes an instance variable :
private int HitCounter = 0;
public int numHits(){
if(read(addr)){ // you should replace addr with some variable that you actually declare
return ++HitCounter;
}
return 0;
}
I also changed return HitCounter++ to return ++HitCounter, since post increment operator (return HitCounter++) will return the old value of HitCounter instead of the incremented value.
EDIT : Another issue is that you pass to read a variable that isn't declared anywhere. You should decide what you want to pass to that method.
public class MotorCar extends Vehicle
{
private String engCap;
public double getLicenseFee()
{
double fee;
if(this.engCap < "1500cc")
{
return fee = 750;
}
else if(this.engCap > "1500cc" && this.engCap < "2500cc")
{
return fee = 900;
}
else(this.engCap > "2500cc")
{
return fee = 1250;
}
}
}
what is wrong with this?
You cannot compare strings (or any other objects) using the less-than < and greater-than > operators.
If you change your engCap variable to an int and drop the "cc" portion, you'll be able to compare it the way you're attempting to.
For example:
public class MotorCar extends Vehicle {
private int engCap;
public double getLicenseFee() {
double fee;
if(this.engCap < 1500) {
return fee = 750;
} else if(this.engCap > 1500 && this.engCap < 2500) {
return fee = 900;
} else(this.engCap > 2500) {
return fee = 1250;
}
}
}
In Java, you cannot use the "<" and ">" (and "<=" and ">=") operators on Strings. To compare the values, use the String#compareTo method, which will return an integer less than zero, equal to zero, or greater than zero, depending on if the String compares less than equal to, or greater than the argument.
Be careful, because this is string comparison, "500cc" will be greater than "1500cc".
EDIT
If you are attempting to determine a range based on the integer portion of engCap, then it would be simpler to go with #thegrinner's answer, and just store the numeric value without the "cc". Then you could use the operators you're attempting to use.