Reputation: 11
I'm writing a simple Java program to do a temperature conversion, and I keep getting an error on line 8 (which I have marked in the code below) that the int cannot be dereferenced. I'm not sure exactly what this means, or how to fix it, and other questions here with the same error did not help with finding a solution for my error. The problem is: having the format:
?<int><int><int><int>
I have to solve the ? in the case, but taking into account the second vector is multiplied by 3, the third by 1 and the fourth by 0 and the last vector is subtracted.
class LeaderBoard{
public static void main(String[] args){
String errorFormat = "Format error: You must write 4 integers and one symbol ?";
int[] list = null;
int position = -1, j = 0;
if(args.length!=5){
System.err.println(errorFormat);
}else{
try {
list = new int[4];
for(int i=0;i<args.length;i++){
if(position== -1 && args[i].equals("?")){
position = i;
}else if((position!= -1 && args[i].equals("?")) || (j==4)){
//Hay mas de un ? o no hay ?
System.err.println(errorFormat);
System.exit(1);
}else{
list[j] = Integer.parseInt(args[i]);
j++;
}
}
} catch (NumberFormatException e) {
System.err.println(errorFormat);
System.exit(1);
}
System.out.println("The missing value is "+calculate(position,list));
}
}
static int calculate(int position, int[] list){
position=0;
for (int i=0; i<list.length; i++){
if(list[1]==0){
position=list[1]*3+list[2]*1+list[3]*0+list[4]*(-1);
}
}
return 0;
}}
When I execute the program I always get the value 0 as a result, altought i change the input values.
Could someone help me?
Upvotes: 0
Views: 186
Reputation: 3440
In your calculate
function you are passing position
but your are not even making use of it and assigning 0
to it.
Also the for loop will throw an exception when i=1 as your code will try to access list[i+4]=list[5] which doesn't exist so will get ArrayIndexOutOfBound Exception
.
Since your array contains only int types you don't need to worry about position of ?
as ?
is not of int type and you can probably use the below code:
static int calculate(int[] list){
int position=0;
int calculatedValue = list[position]*3+list[position+1]*1+list[position+2]*0+list[position+3]*(-1);
return calculatedValue ;
}
Upvotes: 0
Reputation: 12819
list[1]
is a primitive type. You cannot call methods on it. So when you try to call equal
(Did you mean equals()
?) you get an error.
Beyond that your logic doesn't make sense. You're trying to compare an int
to a String
and then compare the boolean result to another int
Upvotes: 2