I'm taking my first java class and we have to add,multiply, divide and subtract rational numbers. but for some reason I keep getting an odd output for my code
public class RatNums {
public static void main (String[] args){
numbers num1;
numbers num2;
num1=new numbers(15,6); //numerator and denominator
num2=new numbers(7,8);
System.out.println(num1.add(num2));
}
}
class numbers{
private double numer,denumi;
public numbers(double num,double denum){ //constructor
numer=num;
denumi=denum;
}
public numbers add(numbers obj){ //The add method
return new numbers((numer * obj.denumi) + (obj.numer*denumi),(denumi*obj.denumi)+(obj.denumi*denumi));
}
}
numbers#2e6e1408
This is the output I get, any ideas?
Related
I'm currently trying to call 2 parseInt methods from main. One converts characters in a char[] to ints and the other just converts String to int.
But I cant figure out the syntax to have main call them.
I tried parseInt(String conString2); and parseInt(char[] conArray);
I couldnt find anything on google about this either.
public class parseInt
{
public static void main(String[] args)
{
parseInt(String);
parseInt(char[] conArray);
}
public static void parseInt(char[] conArray)
{
System.out.println("Original Charaters 1, 2, 3");
char[] conArrray = {1, 2, 3};
int conInt = Integer.parseInt(new String(conArray));
System.out.println("New ints " + conInt);
}
public static void parseInt(String conString2)
{
String conString = "10";
System.out.println("this number will be converted to int from string " + conString );
int conInt2 = Integer.parseInt(conString);
System.out.println(conInt2);
}
}
Im expecting for it to run those methods but instead it gives the errors "cannot be resolved to variable" on conArray and String. I get "Syntax error, insert ". class" to complete " on the char[].
So this is a new one for me. When I try to compare 2 integers, the error tells me that Int should be Void -> Int, which is something I have never even seen before.
The code:
public static function whenTouchEnds(event:TouchEvent){
for (item in currentTouches){
if (item.getId == event.touchPointID){
currentTouches.remove(item);
trace("removed touch");
break;
}
}
}
Following the Haxe documentation, I also tried:
public static function whenTouchEnds(event:TouchEvent){
for (item in currentTouches){
if (item.getId == event.touchPointID) break;
}
}
And for the sake of trail and error (hobby programmer here) even tried:
public static function whenTouchEnds(event:TouchEvent){
for (item in currentTouches){
var itemID:Int = item.getId;
var touchID:Int = event.touchPointID;
if (itemID == touchID){
currentTouches.remove(item);
trace("removed touch");
break;
}
}
}
They all gave me the same error message "Int should be Void -> Int". Here is the Touch class I created which returns an Integer with the getId function:
class Touch
{
public var id:Int = 0;
public var xPos:Int = 0;
public var yPos:Int = 0;
public function new(Id:Int, X:Int, Y:Int)
{
id = Id;
xPos = X;
yPos = Y;
}
public function getX() : Int
{
return (xPos);
}
public function getY() : Int
{
return (yPos);
}
public function getId() : Int
{
return (id);
}
}
I'm not looking for a simple solution, but rather an explanation of what I am missing here. The more I learn, the better!
Cheers
The culprit is this line:
if (item.getId == event.touchPointID)
Since there's no parentheses, you're not actually calling the getId() function here - you're comparing it to an integer (which doesn't make sense). Try this instead:
if (item.getId() == event.touchPointID)
Void -> Int is Haxe's notation for a function type, specifically a function that takes no parameters (Void) and returns an integer. You're comparing such a function to an Int, hence the error message "Int should be Void -> Int".
A small code style critique: the get* functions in your Touch class don't really seem to serve any purpose, the variables are public anyway. If you ever want to do something more complex than just returning the variable in a getter function, you might want to look into using properties instead.
I have a simple comparator as follows:
public class RateComparator implements Comparator<String[]>
{
public int compare(String[] array, String[] anotherArray)
{
return array[0].compareTo( anotherArray[0] );
}
};
But this only sorts values as so:
-.35
-.65
.10
.20
.25
.30
.65
1.0
What my desired behavior is:
-.65
-.35
.10
.20
.25
.30
.65
1.0
How would I accomplish this? All values are strings.
You could cast to floats and compare float vals.
You could, in the comparator, do something like:
public class RateComparator implements Comparator<String[]>
{
public int compare(String[] array, String[] anotherArray)
{
double arrayDouble = Double.parseDouble(array[0]);
double anotherArrayDouble = Double.parseDouble(anotherArray[0]);
return arrayDouble < anotherArrayDouble;
}
};
Instead of writing a comparator I would suggest you to use simple Arrays.sort to short. In this case you need to use double array instead of string array. Find below the sample code
import java.util.Arrays;
public class Testing {
public static void main(String[] args) {
double[] fruits = new double[] {-.35,-.65,.10,.20,.25,.30,.65,1.0};
Arrays.sort(fruits);
for(double arrayElement:fruits){
System.out.println(arrayElement);
}
}
}
I am trying to add a change listener to a the currentTimeProperty of a JavaFX Timeline. I would like to get the value of the current time, and have it represented as a double, so that I can perform operations on that value etc.
At the moment, this is what it looks like:
public void addAnimationListener()
{
animation.getTimeline().currentTimeProperty().addListener(new ChangeListener(){
#Override
public void changed(ObservableValue arg0, Object arg1, Object arg2) {
//double curPercentageValue = arg0.getValue(); //My attempt at trying to get the value to be a double. I tried casting it and such...
System.out.println(arg0.getValue());
}
});
}
The values it prints out are e.g.:
128.33333333333334 ms
...So I could just perform String operations to remove the " ms" and then use Double.parseDouble() to get it to the desired data type...But is there a better way? One which gets the value directly?
Thanks in advance for your help!
These things are always easier to figure out if you properly type your generic types (don't ignore compiler/IDE warnings):
public static void addAnimationListener()
{
animation.getTimeline().currentTimeProperty().addListener(new ChangeListener<Duration>(){
#Override
public void changed(ObservableValue<? extends Duration> observable, Duration oldValue, Duration newValue) {
double millis = newValue.toMillis();
System.out.println(millis + " ms");
}
});
}
In the section on handling Java Beans with Groovy of Groovy In Action, I found this script (slightly modified):
class Book{
String title
}
def groovyBook = new Book()
// explicit way
groovyBook.setTitle('What the heck, really ?')
println groovyBook.getTitle()
// short-hand way
groovyBook.title = 'I am so confused'
println groovyBook.title
There are no such methods in the class Book so how does that work ?
Yes, they are auto defined and calling book.title is actually calling book.getTitle()
See http://groovy.codehaus.org/Groovy+Beans
You can see this in action with the following script:
def debug( clazz ) {
println '----'
clazz.metaClass.methods.findAll { it.name.endsWith( 'Name' ) || it.name.endsWith( 'Age' ) }.each { println it }
}
class A {
String name
int age
}
debug( A )
// Prints
// public int A.getAge()
// public java.lang.String A.getName()
// public void A.setAge(int)
// public void A.setName(java.lang.String)
// Make name final
class B {
final String name
int age
}
debug( B )
// Prints
// public int B.getAge()
// public java.lang.String B.getName()
// public void B.setAge(int)
// Make name private
class C {
private String name
int age
}
debug( C )
// Prints
// public int C.getAge()
// public void C.setAge(int)
// Try protected
class D {
protected String name
int age
}
debug( D )
// Prints
// public int D.getAge()
// public void D.setAge(int)
// And public?
class E {
public String name
int age
}
debug( E )
// Prints
// public int E.getAge()
// public void E.setAge(int)
Several notes:
For all property fields(public ones only), there are autogenerated accesors.
Default visibility is public. So, you should use private/protected keyword to restrict accessor generation.
Inside an accessor there is direct field access. like this.#title
Inside a constructor you have direct access to! This may be unexpected.
For boolean values there are two getters with is and get prefixes.
Each method with such prefixes, even java ones are treated as accessor, and can be referenced in groovy using short syntax.
But sometimes, if you have ambiguous call there may be class cast exception.
Example code for 4-th point.
class A{
private int i = 0;
A(){
i = 4
println("Constructor has direct access. i = $i")
}
void setI(int val) { i = val; println("i is set to $i"); }
int getI(){i}
}
def a = new A() // Constructor has direct access. i = 4
a.i = 5 // i is set to 5
println a.i // 5
4-th note is important, if you have some logic in accessor, and want it to be applied every time you call it. So in constructor you should explicit call setI() method!
Example for 7
class A{
private int i = 0;
void setI(String val) { println("String version.")}
void setI(int val) { i = val; println("i is set to $i"); }
}
def a = new A()
a.i = 5 // i is set to 5
a.i = "1s5" // GroovyCastException: Cannot cast object '1s5' with class 'java.lang.String' to class 'int'
So, as I see property-like access uses first declared accessor, and don't support overloading. Maybe will be fixed later.
Groovy generates public accessor / mutator methods for fields when and only when there is no access modifier present. For fields declared as public, private or protected no getters and setters will be created.
For fields declared as final only accessors will be created.
All that applies for static fields analogously.