Int cannot be dereferenced with getText() [duplicate] - java

I'm fairly new to Java and I'm using BlueJ. I keep getting this "Int cannot be dereferenced" error when trying to compile and I'm not sure what the problem is. The error is specifically happening in my if statement at the bottom, where it says "equals" is an error and "int cannot be dereferenced." Hope to get some assistance as I have no idea what to do. Thank you in advance!
public class Catalog {
private Item[] list;
private int size;
// Construct an empty catalog with the specified capacity.
public Catalog(int max) {
list = new Item[max];
size = 0;
}
// Insert a new item into the catalog.
// Throw a CatalogFull exception if the catalog is full.
public void insert(Item obj) throws CatalogFull {
if (list.length == size) {
throw new CatalogFull();
}
list[size] = obj;
++size;
}
// Search the catalog for the item whose item number
// is the parameter id. Return the matching object
// if the search succeeds. Throw an ItemNotFound
// exception if the search fails.
public Item find(int id) throws ItemNotFound {
for (int pos = 0; pos < size; ++pos){
if (id.equals(list[pos].getItemNumber())){ //Getting error on "equals"
return list[pos];
}
else {
throw new ItemNotFound();
}
}
}
}

id is of primitive type int and not an Object. You cannot call methods on a primitive as you are doing here :
id.equals
Try replacing this:
if (id.equals(list[pos].getItemNumber())){ //Getting error on "equals"
with
if (id == list[pos].getItemNumber()){ //Getting error on "equals"

Basically, you're trying to use int as if it was an Object, which it isn't (well...it's complicated)
id.equals(list[pos].getItemNumber())
Should be...
id == list[pos].getItemNumber()

Dereferencing is the process of accessing the value referred to by a reference . Since, int is already a value (not a reference), it can not be dereferenced.
so u need to replace your code (.) to(==).

Assuming getItemNumber() returns an int, replace
if (id.equals(list[pos].getItemNumber()))
with
if (id == list[pos].getItemNumber())

Change
id.equals(list[pos].getItemNumber())
to
id == list[pos].getItemNumber()
For more details, you should learn the difference between the primitive types like int, char, and double and reference types.

As your methods an int datatype, you should use "==" instead of equals()
try replacing this
if (id.equals(list[pos].getItemNumber()))
with
if (id.equals==list[pos].getItemNumber())
it will fix the error .

I think you are getting this error in the initialization of the Integer somewhere

try
id == list[pos].getItemNumber()
instead of
id.equals(list[pos].getItemNumber()

Related

How to ensure that an element in the IntArray has not been assigned a value in Kotlin?

class Solution {
private Integer[][] memory = //whaterver, It doesn't matter.
public int leetcode(int[] array) {
return Math.max(dfs(0, 0), dfs(0, 1));
}
int dfs(int status1, int status2) {
if (status1 == Integer.MAX_VALUE || status2 == Integer.MAX_VALUE) {
return 0;
}
if (memory[status1][status2] != null) {
return memory[status1][status2];
} else {
memory[status1][status2] = calculate() + Math.max(dfs(status1 + 1, status2), dfs(status1 + 1, status2 + 1));
return memory[status1][status2];
}
}
Integer calculate() {
//...
}
}
As shown in the above java code, in java, you can use null to judge whether an element in the array has memorized a certain value. If memorized, you can use it directly. If not, you need to do some calculations and then store the calculated value.
In Kotlin, since IntArray does not accept null, is there any good way to achieve similar operations?
thanks a lot.
You can make a variable accept nulls by using ?
In Kotlin, the type system distinguishes between references that can hold null (nullable references) and those that cannot (non-null references). For example, a regular variable of type String cannot hold null:
var a: String = "abc" // Regular initialization means non-null by default
a = null // compilation error
To allow nulls, you can declare a variable as nullable string, written String?:
var b: String? = "abc" // can be set null
b = null // ok
print(b)
You want an Int array that accepts null so write:-
fun main() {
val emptyArray : Array<Int?> = arrayOfNulls(0)
println(emptyArray.size) // 0
}
Check this documentation on null safety for all the details.Comment for any follow up query
Hope you found this answer useful, if so please accept it by clicking the ✔(tick symbol) next to it. Have a nice day :)

Object as a key in treemap in java 8

CompareObj is a class in java It consists of three attributes String rowKey, Integer hitCount, Long recency
public CompareObj(String string, Integer i) {
this.rowKey = string;
this.hitCount = i%10;
this.recency= (Long) i*1000;
}
Now I created a treeMap
Comparator<CompareObj> comp1 = (e1,e2) -> e1.getHitCount().compareTo(e2.getHitCount());
Comparator<CompareObj> comp2 = (e1,e2) -> e2.getRecency().compareTo(e1.getRecency());
Comparator<CompareObj> result = comp1.thenComparing(comp2);
TreeMap<CompareObj, CompareObj> tM = new TreeMap<CompareObj, CompareObj>(result);
for(int i=0;i<=1000;i++)
{
CompareObj cO = new CompareObj("A"+i, i);
tM.put(cO,cO);
}
for(int i=0;i<=1000;i++)
{
CompareObj cO = new CompareObj("A"+i, i);
CompareObj values = tM.get(cO);
System.out.println(values.getRowKey()); // Line 28: get Null Pointer Exception
}
Also I overide hashCode and Equals. Still I get nullponter exception.
#Override
public int hashCode() {
return Objects.hash(getRowKey());
}
#Override
public boolean equals(Object obj) {
if(this==obj) return true;
if(!(obj instanceof CompareObj)) return false;
CompareObj compareObj = (CompareObj) obj;
return Objects.equals(this.getRowKey(), compareObj.getRowKey());
}
Here when I try to retrive value from treemap back I get Null Pointer exception in the line mentioned. How to solve this
If I want to implement comapareTo() of Comaprable interface, how should I implement if there is multiple sort conditions.
The first thing to understand, is the NullPointerException. If you get that exception on the exact line
System.out.println(values.getRowKey());
then either System.out or values is null. Since we can preclude System.out being null, it’s the values variable, which contains the result of get and can be null if the lookup failed.
Since you are initializing the TreeMap with a custom Comparator, that Comparatordetermines equality. Your Comparator is based on the properties getHitCount() and getRecency() which must match, which implies that when the lookup fails, the map doesn’t contain an object having the same values as reported by these two methods.
You show that you construct objects with the same values but not the code of these getters. There must be an inconsistency. As Misha pointed out, your posted code can’t be the code you have ran when getting the exception, therefore we can’t help you further (unless you post the real code you ran).

What to return as the minimum element of an empty heap

I have written this simple code to check weather a binary heap is empty or not. I have problem with return. It can not be: null, void, or nothing; It should return something int, but I don't know what. So, what should I put there, if I want to keep this code simple? (I mean not using Integer class or java.lang.Integer).
public int getMinimum() {
if (isEmpty()) {
System.out.println("Heap is empty");
return;
} else
return data[0];
}
throw a exception for invalid value and handle it when calling
public int getMinimum() throws Exception {
if (isEmpty())
throw new Exception("Heap is Empty");
else
return data[0];
}
and when getting minimum
try{
int i = getMinimum();
System.out.println("Minimum is :" + i);
}catch(Exception e){
System.out.println(e.getMessage());
}
I can only help with elimination... java is not magic. If you declare your function to return an "int", then the compiler will make you return an int.
Which leaves limited options:
1) throw an exception, and teach your users to use it in combination with 'isEmpty()', e.g.:
if(theHeap.isEmpty()) System.out.println("empty");
else System.out.println(theHeap.getMinimum())
2) use that Integer which you didn't like (I'm guessing, for performance reasons?)
3) find some int value that's not likely to be present in the data, e.g. perhaps you don't expect your heap to ever hold Integer.MIN_VALUE.
If your heap contained doubles, i'd recommend NaN.
That's all that's available in the java syntax, sorry it's not ground braking...
int is a primitive and therefore needs to have a value.
If you really want to solve it like this, you need to specify a certain int value that would never appear in the heap. You could also try throwing an exception when heap is empty.
we can simply declare it is "Integer" instead of "int", so we can return "null", as well.
public Integer getMinimum(){
if(isEmpty())
return null;
else
return data[0];
}

Trying to understand data validation of set methods in true/false format

I am currently working on a project that involves creating an array of objects(in this case, hardware tools from a created ToolItem class), and then creating a class file manipulate this data. The class I am creating now, named HardwareStore, has methods to search, insert and delete private data members for items in my array. Using a method named assign() from the previously mentioned ToolItem class, I call the set methods for each data member and assign them to a spot in the array. Assign looks like:
public void assign(int quality, String name, int id, int numInStock, double price)
{
setQuality(quality);
setToolName(name);
setID(id);
setNumberInStock(numInStock);
setPrice(price);
}
My insert method currently looks like:
public int insert(int quality, String name, int id, int numInStock, double price)
{
//testing the unique ID passed by the user,
//making sure there isn't an object in the
//array with the same ID
testArray = searchArray(id);
//array holds a max of 10 objects
if (numberOfItems == 10)
{
System.out.println("Array is full");
return 0;
}
//-1 is sentinel value from search method,
//telling me there isn't an object with the
//same specified ID
else if (testArray == -1)
{
for (index = 0; index < toolArray.length; index++)
{
if (toolArray[index].getToolID() == 0)
{
toolArray[index].assign(quality, name, id, numInStock, price);
numberOfItems++; //counter for array
return 1;
}
}//end for loop
}
return -1; //sentinel value telling me there was a dupe ID
}//end insert
I am supposed to validate the toolArray[index].assign(quality, name, id, numInStock, price); using a boolean variable in this manner, though:
boolean oK = toolArray[index].assign(quality, id, numInStock, price);
If oK == true, I then increment the number of items in the array. In order for this to work, I would need assign() to have a return type of boolean. This is how it was explained to me:
Yes you will want an Assign method. All that goes into it are calls to "set" values to there appointed places.
The assign method will return a value depending on whether or not the value was assigned/inserted. You will need to check the value of oK to make sure it is true or false.
My issue is, I do not know how to change the assign() return type to boolean and make the method work properly. My first thought was something like:
if (setQuality(quality) == true)
{
return true;
}
else if (setToolName(name) == true)
{
return true;
}
else
return false;
but this obviously doesn't work and results in several compiler errors :/ I just don't understand the logic behind this kind of data checking. If someone understands this and could help me, I would greatly appreciate it!
Well, considering that your assign method only contains setter methods that assign primitive values or Strings to inner fields, there isn't much that can go wrong with that so the simplest way to achieve what you want is just to return true at the end of assign():
public boolean assign(int quality, String name, int id, int numInStock, double price)
{
setQuality(quality);
setToolName(name);
setID(id);
setNumberInStock(numInStock);
setPrice(price);
return true;
}
Now if you have specific values that are illegal for your parameters, for example a negative integer for id, or null for the name, you can add a check inside each of your setter methods for the illegal values. If those values get passed you can throw an Exception such as IllegalArgumentException or you can make a custom exception even if you'd like. Here's how it would look for the setID() method:
void setID(int id) throws IllegalArgumentException {
if(id < 0) {
throw new IllegalArgumentException();
} else {
this.id = id;
}
}
Then, assuming all of your setters throw the same exception, you can add a try/catch block to the assign() method and return false if any the setter methods received the illegal values. Code would look like:
public boolean assign(int quality, String name, int id, int numInStock, double price)
{
try {
setQuality(quality);
setToolName(name);
setID(id);
setNumberInStock(numInStock);
setPrice(price);
} catch (IllegalArgumentException iae) {
return false;
}
return true;
}
If your methods need to throw different exceptions for some reason, then you can separate exception in the catch block like:
catch (ExceptionOne e1 | ExceptionTwo e2 ....) {
return false;
}
Using Exceptions is ok in this case since having one of these values be invalid is a systematic logic failure and should be noted. An illegal id or name corrupts your system logic and therefore should be handled with a proper exception. Also, this will probably never happen or happen very rarely so it would literally be an "exception" to the logic of your program.
However, if for example, you had a function that asks the user for the name of a tool they want and the user gives you an invalid tool name, you don't need to throw an exception there because that doesn't make your system have an error, that's just user not knowing how to use the system or just not knowing his tool names. In that case you can just return an error value like null or false.
Notice that I changed the return type... from void to boolean
public boolean assign(int quality, String name, int id, int numInStock, double price)
{
return
(setQuality(quality) &&
setToolName(name) &&
setID(id) &&
setNumberInStock(numInStock) &&
setPrice(price))
}
Then, notice that I changed the sentences with a condition. If I say return A && B it means that it will return true if both A and B are true, so, following that logic, you construct the entire return sentence and save yourself lots of Ifs..
Using exceptions as flow control structure is a bad practice and antipattern.

NullPointerException and the best way to deal with it

Note: This is homework/assignment feel not to answer if you don't want to.
Ok after some search and reading these:
How to check if array element is null to avoid NullPointerException in Java
Gracefully avoiding NullPointerException in Java
http://c2.com/cgi/wiki?NullPointerException
Am still not making any progress on how to deal with NullPointerException error on my code, snippet for questionable code:
int findElement(String element) {
int retval = 0;
for ( int i = 0; i < setElements.length; i++) {
if ( setElements[i].equals(element) ) { // This line 31 here
return retval = i;
}
else {
return retval = -1;
}
}
return retval;
}
void add(String newValue) {
int elem = findElement(newValue);
if( numberOfElements < maxNumberOfElements && elem != -1 ) {
setElements[numberOfElements] = newValue;
numberOfElements++;
} else { System.out.println("Element " + newValue + "already exist"); }
}
It compile but adding new element to a set throws a NullPointerException error.
D:\javaprojects>java SetDemo
Enter string element to be added
A
You entered A
Exception in thread "main" java.lang.NullPointerException
at Set.findElement(Set.java:31)
at Set.add(Set.java:44)
at SetDemo.main(Set.java:145)
I added another check, though honestly don't have clue if this right to line 31.
if ( setElements != null && setElements[i].equals(element) ) but still no joy.
A documentation/tips or explanation is greatly appreciated.
learning,
lupin
Did you initialize setElements anywhere? Meaning:
String[] setElements = new String[100];
If you simply declare an array variable:
String[] setElements;
as a data member of your class it is initialized to null. You have to make it point to something. You can either do this inline:
public class MyClass {
private String[] setElements = new String[100];
...
}
or in a constructor:
public class MyClass {
private String[] setElements;
public MyClass() {
setElements = new String[100];
}
...
}
The for-loop in findElement doesn't make sense.
for ( int i = 0; i < setElements.length; i++) {
if ( setElements[i].equals(element) ) { // This line 31 here
return retval = i;
}
else {
return retval = -1;
}
}
You should iterate through all values before returning -1, only then do you know that there is no element in the set that matches element.
Post the entire class - this snippet is useless.
You're making two serious mistakes: failing to believe the compiler, and assuming that your code is correct.
If the JVM tells you that line 31 is the problem, believe it.
My guess is that setElements[i] is null.
It should be setElements[i] != null && setElements[i].equals(element). If a collection contains null elements you will try to dereference a null reference when you call equals method on that element.
As for NullPointerException - you should never catch it. For things that shouldn't be null, they must be initialized properly. For those things that cannot be null - they must be checked for null before dereferencing them (i.e. calling methods on them).
The only use case for catching NullPointerException is when you are using a third-party library that you don't have the source for and has a bug that causes NullPointerException to be thrown. These cases are rare and since you only beginning to learn Java, forget that I mentioned this and concentrate on more important things.
Try testing the element itself for null, not the array:
setElements[i] != null && setElements[i].equals(element)
You should not attempt to catch a null pointer exception. Instead, the best way to avoid null pointers is:
In any function that takes parameters where you assume that the parameter is non-null, always check that the parameter is non-null and throw an IllegalArgumentException if it is null.
Whenever you invoke a function that does not allow null parameters, ensure that you do not pass a null pointer to that function; if you already know that the object is non-null (because you already checked it and would have thrown an IllegalArgumentException), then you do not need to recheck; otherwise, you should double-check that the object is non-null before passing it along.
Since you do not check the parameters to your findElement and add functions, it is quite possible that the parameters are the culprits. Add the appropriate check and throw IllegalArgumentException if they are null. If, after you do that, you get an IllegalArgumentException, then you've solved your problem. If not, then you at least know that the problem is not the parameter and is elsewhere in the code.
Its working now, thanks to Lars,Igor and the rest who took time to critic the code, there's a logic error that wasn't check,anyway here's the corrected working code, lastly I'm bother am I doing cheating? :(
int findElement(String element) {
int retval = 0;
for ( int i = 0; i < setElements.length; i++) { //loop first to the array and only return -1 once we can't find it.
//setElements[i] != null is the NullPointerException killer :)
if ( setElements[i] != null && setElements[i].equals(element) ) {
return retval = i;
}
retval = -1;
}
return retval;
}
void add(String newValue) {
int elem = findElement(newValue);
if( numberOfElements < maxNumberOfElements && elem == -1 ) { # == instead of != as I only need to add if elements is non-existing
setElements[numberOfElements] = newValue;
numberOfElements++;
}
}
with thanks,
lupin

Categories