Для решения одной задачи мне надо округлить результат деления Integer/Integer до большего целого числа (если он будет являться дробью).
Чтобы решить эту задачу я нашёл две конструкции:
Конструкция 1:
int a = 1;
int b = 3;
int x = (a+(b-1))/b;
Конструкция 2:
int a = 1;
int b = 3;
int x = Math.ceil((double)a / b).intValue();
Как я понимаю, единственно правильным будет использовать конструкцию 2, т.к. конструкция 1 работает не для всех значений (например, отрицательные b).
Проблема в том, что в своём коде при компиляции я получаю непонятную мне ошибку, на которую я не нашёл самостоятельного ответа:
java: double cannot be dereferenced
Пример моего кода:
public class Main {
public static void main(String[] args) {
int h = 20;
int up = 7;
int down = 3;
int predUpDays = h - up;
int progress = up - down;
int days = Math.ceil((double)predUpDays / progress).intValue();
days++;
System.out.println(days);
}
}
Что я делаю не так?
import java.awt.Rectangle;
import java.util.Comparator;
public class RectangleComparator implements Comparator
{
public int compare(Object object1, Object object2)
{
Rectangle rec1 = (Rectangle) object1;
Rectangle rec2 = (Rectangle) object2;
return rec1.getWidth().compareTo(rec2.getWidth());
}
}
For some reason, I’m getting the error double cannot be dereferenced. Can anyone help me figure out why?
asked Sep 9, 2013 at 4:50
1
To compare two double
primitives:
Java old school:
return new Double(rec1.getWidth()).compareTo(new Double(rec2.getWidth());
Java 1.4 onwards:
return Double.compare(rec1.getWidth(), rec2.getWidth());
answered Sep 9, 2013 at 5:01
Bohemian♦Bohemian
409k90 gold badges570 silver badges715 bronze badges
10
rocketboy is correct with regard to why this is happening.
Consider using the Double wrapper class like this
new Double(rec1.getWidth()).compareTo(rec2.getWidth());
Only the first value need to be converted to a wrapper Double, the second one will be auto boxed.
answered Sep 9, 2013 at 4:56
ThiharaThihara
7,0212 gold badges29 silver badges56 bronze badges
4
I think your Rectangle.getWidth()
returns a double
. It is not a wrapper Object like Double, so the dot operator cannot be used.
Had it been:
Double getWidth()
instead of double getWidth()
then rec1.getWidth().compareTo(rec2.getWidth());
would have been valid.
How to compare doubles in Java?
answered Sep 9, 2013 at 4:52
rocketboyrocketboy
9,5432 gold badges34 silver badges36 bronze badges
0
Вопрос:
String mins = minsField.getText();
int Mins;
try
{
Mins = Integer.parseInt(mins);
}
catch (NumberFormatException e)
{
Mins = 0;
}
double hours = Mins / 60;
hours.setText(hoursminsfield);
Проблема заключается в том, что Double cannot be dereferenced
.
Лучший ответ:
EDIT 4/23/12
double cannot be dereferenced
– это ошибка, которую некоторые компиляторы Java дают, когда вы пытаетесь вызвать метод на примитиве. Мне кажется, что double has no such method
будет более полезным, но что я знаю.
Из вашего кода кажется, что вы думаете, что можете скопировать текстовое представление hours
в hoursminfield
, выполнив hours.setText(hoursminfield);
У этого есть несколько ошибок:
1) часов – это double
, который является примитивным типом, и нет методов, которые вы можете вызвать. Это то, что дает вам ошибку, о которой вы просили.
2) вы не говорите, какой тип hoursminfield, может быть, вы еще не объявили его.
3) необычно устанавливать значение переменной, считая ее аргументом для метода. Это случается иногда, но не обычно.
Строки кода, которые делают то, что вам кажется нужным, следующие:
String hoursrminfield; // you better declare any variable you are using
// wrap hours in a Double, then use toString() on that Double
hoursminfield = Double.valueOf(hours).toString();
// or else a different way to wrap in a double using the Double constructor:
(new Double(hours)).toString();
// or else use the very helpful valueOf() method from the class String which will
// create a string version of any primitive type:
hoursminfield = String.valueOf(hours);
ОРИГИНАЛЬНЫЙ ОТВЕТ (обратился к другой проблеме в вашем коде):
В double hours = Mins / 60;
вы разделите два int
s. Вы получите значение int
этого деления, так что если Mins = 43; двойные часы = мин /60; //Mins/ 60 – это int = 0. Назначая его двойным часам, // часы удваиваются, равные нулю.
Что вам нужно сделать:
double hours = Mins / ((double) 60);
или что-то в этом роде, вам нужно отбросить часть вашего деления на double
, чтобы заставить деление сделать с помощью double
, а не int
s.
Ответ №1
Вы не указали язык, но, если это Java, существует большая разница между базовым типом double
и классом double
.
В любом случае ваш setText
кажется неправильным. Метод setText
относится к полю данных, а не к данным, которые вы пытаетесь вставить:
hoursminsfield.setText (hours);
Другими словами, вы хотите установить текст поля, используя двойной вы только что рассчитали. Если вы можете пройти двойное, это другое дело, которое может потребоваться изучить.
Другое дело:
double hours = Mins / 60;
будет, если Mins
является целым числом, дайте вам целочисленное значение, которое вы затем положите в double. Это означает, что он будет усечен. Если вы хотите, чтобы вы сохраняли точность после разделения, вы можете использовать что-то вроде:
double hours = (double) Mins / 60.0;
(хотя он может работать только с одним из этих изменений, я предпочитаю делать все выражения явными).
Ответ №2
Как насчет этого пути
double hours = Mins / 60.0
Я всегда использую вышеуказанный оператор, чтобы получить двойное значение
Solution 1
EDIT 4/23/12
double cannot be dereferenced
is the error some Java compilers give when you try to call a method on a primitive. It seems to me double has no such method
would be more helpful, but what do I know.
From your code, it seems you think you can copy a text representation of hours
into hoursminfield
by doing
hours.setText(hoursminfield);
This has a few errors:
1) hours is a double
which is a primitive type, there are NO methods you can call on it. This is what gives you the error you asked about.
2) you don’t say what type hoursminfield is, maybe you haven’t even declared it yet.
3) it is unusual to set the value of a variable by having it be the argument to a method. It happens sometimes, but not usually.
The lines of code that do what you seem to want are:
String hoursrminfield; // you better declare any variable you are using
// wrap hours in a Double, then use toString() on that Double
hoursminfield = Double.valueOf(hours).toString();
// or else a different way to wrap in a double using the Double constructor:
(new Double(hours)).toString();
// or else use the very helpful valueOf() method from the class String which will
// create a string version of any primitive type:
hoursminfield = String.valueOf(hours);
ORIGINAL ANSWER (addressed a different problem in your code):
In double hours = Mins / 60;
you are dividing two int
s. You will get the int
value of that division, so if
Mins = 43;
double hours = Mins / 60;
// Mins / 60 is an int = 0. assigning it to double hours makes
// hours a double equal to zero.
What you need to do is:
double hours = Mins / ((double) 60);
or something like that, you need to cast some part of your division to a double
in order to force the division to be done with double
s and not int
s.
Solution 2
You haven’t specified the language but, if it’s Java, there’s a big difference between the basic type double
and the class Double
.
In any case, your setText
seems the wrong way around. The setText
method would belong to the data field, not the data you’re trying to put in there:
hoursminsfield.setText (hours);
In other words, you want to set the text of the field, using the double you just calculated. Whether you can pass a double is a different matter which may need to be examined.
Another thing:
double hours = Mins / 60;
will, if Mins
is an integer`, give you an integer value which you then put into a double. That means it will be truncated. If you want to ensure you keep precision following the division, you can use something like:
double hours = (double) Mins / 60.0;
(though it may work with only one of those changes, I prefer to make all terms explicit).
Comments
-
String mins = minsField.getText(); int Mins; try { Mins = Integer.parseInt(mins); } catch (NumberFormatException e) { Mins = 0; } double hours = Mins / 60; hours.setText(hoursminsfield);
The problem is that
Double cannot be dereferenced
. -
Yeah its java my bad, but can you tell me how i can fix this? please? lol
-
Uhm, they did. you can’t call
setText
on a Double because a Double is just a number. It doesn’t have asetText
method because it doesn’t have any text… -
ahh ok i get ya, can you suggest what i can do then? cause im pretty new at this and have nearly no idea what to do
-
@Daniel, examine my code snippet very carefully. I’ve swapped over
hourminsfield
andhours
from what you had. That’s your first step. -
i inserted Double.toString(hours), was that right to do? :S cause now it doesnt really give me the right answer, like if i put in 240 mins it give me 4 hours but if i put in 256 mins it still gives me 4 hours
-
Try changing your assignment to something like
double hours = (double) Mins / 60.0;
. When you divide an integer by 60, you get an integer, not matter where you eventually put the result. -
I am puttin up another problem i am having if you would be so awesome to give me some advice on aswell, would be greatly appreciated.
-
I am puttin up another problem i am having if you would be so awesome to give me some advice on aswell, would be greatly appreciated.
-
@Daniel, SO is not a message board. If you have a different problem, ask a different question.
-
This is great, an accepted answer that is correct, and I’m getting downvoted! Maybe one of you power users downvoting could tell me why.
-
@mwengler It actually doesn’t answer the question. The question was about what was causing the error
Double cannot be dereferenced
. The fact that your answer was accepted is inconsequential (and actually just draws more attention to the fact that it is incorrect). -
@Zshazz I guess the experts would know better who answered his question than questioner would. I’ll know to edit the question next time before answering what the questioner really meant.
Recents
That error means that you tried to invoke a method on a double
value – in Java, double
is a primitive type and you cant call methods on it:
stable1.findHorseFeed(1).horseFeed()
^ ^
returns a double cant call any method on it
You need to invoke the method on the correct object, with the expected parameters – something like this:
Horse aHorse = new Horse(...);
aHorse.horseFeed(stable1.findHorseFeed(1));
The method horseFeed()
is in the Horse
class, and it receives a parameter of type double
, which is returned by the method findHorseFeed()
in the HorseStable
class. Clearly, first you need to create an instance of type Horse
to invoke it.
Also, please follow the convention that class names start with an uppercase character.
findHorseFeed()
returns a double
, on which you cannot call the horseFeed()
method (it returns a double
, not a horse
object)
First you need to write (and subsequently call) another method to return a horse object that you can then call horseFeed()
on.
In class horseStable
youll want a method like
public horse findtHorse(int i) {
horse myhorse = horseList.get(i);
return myhorse
}
You can probably also refactor findHorseFeed
to just .getWeight()
on getHorse()
:
public double findHorseFeed(horse myhorse) {
double weight = myhorse.getWeight();
return weight
}
then you can call:
horse myHorse = stable1.findHorse(1);
String range = myHorse.horseFeed(stable1.findHorseFeed(myHorse));