public class Fraction
{
public Franction(int n, int d)
{
int num = n;
int denom = d;
}
public static void main(String[] args)
{
Fraction f1 = new Fraction(5,10);
System.out.println("Fraction = " + f1);
}
}
Hello, I'm trying to learn Java... The book I'm working out of suggests that the output of the code above should print "Fraction = 5/10", but when I try it I just receive "Fraction = Fraction#33469a69" which I assume is printing the reference to where it is stored? I understand how it is suppose to work with the constructor I just don't receive the expected output. Any help would be greatly appreciated... Thanks!
To get the desired output, you need to overload toString() method in the Franction class. This method is used to determine textual representation of the object. By default, it is ClassName#hashCode.
Also, you probably would like to store the values you receive in the constructor as fields. Right now, you store the numerator and denominator in constructor's local variables, that are destroyed as soon as the constructor exits.
Try something like this:
public class Fraction
{
private final int num
private final int denom;
public Franction(int n, int d)
{
this.num = n;
this.denom = d;
}
#Override
String toString()
{
return String.format("%d/%d", num, denom);
}
public static void main(String[] args)
{
Fraction f1 = new Fraction(5,10);
System.out.println("Fraction = " + f1);
}
}
You need to override the toString method for the same
public String toString(){
StringBuilder stringToReturn = new StringBuilder();
stringToReturn.append(this.num);
stringToReturn.append("/");
stringToReturn.append(this.denom);
return stringToReturn.toString();
}
You have to override the toString() function in your Fraction class.
As per docs of toString()
Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object.
So
Fraction#33469a69 is the textual representation of Fraction class.
To get the required output, write the logic in overridden toString method in Object class and return the string there.
A simple toString implementation looks like
#Override
public String toString() {
StringBuilder result = new StringBuilder();
result.append(this.someMemeber); //will be in String format
result.append(this.someMemeber);
return result.toString();
}
Try this
public class Fraction
{
private int num;
private int denom;
public Franction(int n, int d)
{
num = n;
denom = d;
}
public int getNum()
{
return num;
}
public int getDenom()
{
return denom;
}
public static void main(String[] args)
{
Fraction f1 = new Fraction(5,10);
System.out.println("Fraction = " + f1.getNum() + "/" + f1.getDenom());
}
}
Alternative (Better way to do this)
public class Fraction
{
private int num;
private int denom;
public Franction(int n, int d)
{
num = n;
denom = d;
}
public int getNum()
{
return num;
}
public int getDenom()
{
return denom;
}
#Override
public String toString(){
return (f1.getNum() + "/" + f1.getDenom());
}
public static void main(String[] args)
{
Fraction f1 = new Fraction(5,10);
System.out.println("Fraction = " + f1 );
}
}
You need to study more about encapsulation , the Object class and the toString() method.
Happy Coding :)
Try the following:
public class Fraction {
private final int num;
private final int denom;
public Fraction(int num, int denom) {
this.num = num;
this.denom = denom;
}
#Override
public String toString() {
return num + "/" + denom;
}
public static void main(String[] args) {
Fraction f1 = new Fraction(5, 10);
System.out.println("Fraction = " + f1);
}
}
You have to store the values in the object you create. Then override the toString method of Object to get your desired output.
Output:
Fraction = 5/10
All you are doing is printing out the Object.
If you want to print the contents of the Object you will to create a toString method in you class.
see http://www.javapractices.com/topic/TopicAction.do?Id=55
Related
This question already has an answer here:
What does "error: '.class' expected" mean and how do I fix it
(1 answer)
Closed 4 months ago.
I was trying to create a java program that adds 2 numbers but keep getting this error
error: '.class' expected
return int ad();
1 error
error: compilation failed
Here is my code
public class Sum {
int a;
int b;
int add;
public int ad(int a, int b){
int add = (int) a + b;
return add;
}
public static void main(String[] args) {
return int ad();
}
}
public class Sum {
/*
int a;
int b;
int add;
*/
public int ad(int a, int b) {
return a + b;
}
public static void main(String[] args) {
int sum = ad(1, 3);
System.out.println(sum);
}
}
main()'s return type is void - it cannot return anything. Mostly it is used to call functions.
Pass parameters to ad() - or you will get a compile time exception - it is expecting 2 integers.
Redundant casting here: int add = (int) a + b; - for a simple method like this, you can directly return a + b;
Unused variables - all your member variables are unused.
Solution 2 (using member variables):
public class Sum {
private int a;
private int b;
private int ad() {
return a + b;
}
public static void main(String[] args) {
Sum s = new Sum();
s.a = 1;
s.b = 2;
int sum = s.ad();
System.out.println(sum);
}
}
There are some points in your code:
main() can't return anything because it's a void method.
You don't have to use member variables in this situation. Member variables are most used in classes. Like for instance when you want to create a Person class.
You don't have to type int add = (int) a + b because you don't have to convert anything.The datatype is already an int.
Here's an example of what you can do:
public class Main {
public int add(int a, int b){
int result = a + b;
return result;
}
public static void main(String[] args) {
Main main = new Main();
System.out.println(main.add(1, 1));
}
}
Output:
2
Hope this information was useful!
The method "public static void main(String[] args)" is static and the method "public public int ad(int a, int b)" is non-static.
If you want to reach the method "public int ad(int a, int b)" then make an instance of class Sum and call the method "ad(int a, int b)", or make the method "ad(int a, int b)" static. As already mentioned in comments above, "public static void main(String[] args)" has no return type - it is void, so no "return int ad()" in main method is needed.
Alrernative 1 - Make an instance of class Sum and call method ad(int a, int b):
public class Sum {
int a;
int b;
int add;
public int ad(int a, int b) {
int add = (int) a + b;
return add;
}
public static void main(String[] args) {
Sum sum = new Sum(); // Make an instance of class Sum
int result = sum.ad(1, 2); // and call method ad
System.out.println("Result: " + result); // Output: 'Result: 3'
}
}
Alternative 2 - Make method ad(int a, int b) static:
public class Sum {
public static int ad(int a, int b) { // Make method ad static
int add = (int) a + b;
return add;
}
public static void main(String[] args) {
int result = Sum.ad(1, 3); // Calling static method ad
System.out.println("Result: " + result); // Output: 'Result: 3'
}
}
Read more about diffrence between static and non-static methods here:
https://stackoverflow.com/questions/3903537/what-is-the-difference-between-a-static-method-and-a-non-static-method#:~:text=A%20static%20method%20belongs%20to%20the%20class%20and%20a%20non,class%20that%20it%20belongs%20to.&text=In%20the%20other%20case%2C%20a,class%20has%20already%20been%20instantiated.
In my QuestionnaireUI.java class
private void btnProceedActionPerformed(java.awt.event.ActionEvent evt) {
tblResults.setRowSelectionAllowed(true);
int temp = tblResults.getSelectedRow();
Global.manu = tblResults.getValueAt(temp, 1).toString();
Global.mod = tblResults.getValueAt(temp, 2).toString();
Global.price = "R" + (Integer)tblResults.getValueAt(temp,3).toString(); //line of code that gives me the error message
this.dispose();
new PaymentUI().setVisible(true);
}
In my Global.java class that I use for all my global variables
public class Global {
public static int rowSelect;
public static String manu;
public static String mod;
public static int price;
public static int financeprice;
public static int rate = 9;
}
you are Adding R (a String) to (Integer)tblResults.getValueAt(temp,3).toString()
There are a few issues here:
tblResults.getValueAt(temp,3).toString() returns a String, which is not an integer so can not be cast to an integer.
Adding a String to anything will always give you a String, so "R" + something will always return a String. which you are then trying to assign to an Integer.
As the + operator with String as one of the arguments converts the other argument to String:
Global.price = "R" + tblResults.getValueAt(temp,3);
Unless price declared as int in which case:
Global.price = (Integer)tblResults.getValueAt(temp,3);
class Maths{
// Attributes of maths
private int num1;
private int num2;
//Constructor
public Maths ***- This is where the error is***
{
add = a;
subtract = s;
multiply = m;
divide = d;
}
//Get me some Accessors
public String getAdd()
{
return add;
}
public string getSubtract()
{
return subtract;
}
public String getMultiply()
{
return multiply;
}
public String getDivide()
{
return divide;
}
}
}
Alright so I'm new to programming, Absolutely newborn. I'm really not sure what to do for this. I need to "Write a class called Maths. It has 2 attributes called num1 and num2. It has a constructor. It will have methods called Add(), subtract(), multiply() and divide().(Hint: integer division use modulus operator). Most of these methods return the result.
Write all the getters and setters and a toString() method."
In Maths constructor you have forgotten parenthesis ()
Do like this
public Maths()
{
add = a;
subtract = s;
multiply = m;
divide = d;
}
constructor has the same name as class and parenthesis.
this is what you need to put there.
public Maths()
{
add = a;
subtract = s;
multiply = m;
divide = d;
}
I'm writing a program that simulates simple bank account activities and I was wondering how to do it so that if I create a new Account without any parameters, it receives random 7digit identification number that is shown as String. The way I do, I only receive java.util.Random#2a0364ef in output.
Looking forward to any help and additional comments on this question as it is the first one I've posted on this website.
import java.util.Random;
class Account {
String id;
double stan;
int num;
static int counter;
public Account() {
**id = randomId().toString();**
stan = 0;
num = ++counter;
}
public Account(String id) {
this.id = id;
stan = 0;
num = ++counter;
}
public Account(String id, double mon) {
stan = 0;
this.id = id;
this.stan = mon;
num = ++counter;
}
**static String randomId() {
Random rand = new Random(7);
return String.valueOf(rand);**
}
String getId() {
return id;
}
double getStan() {
return stan;
}
int getNum() {
return num;
}
#Override
public String toString() {
return "Account's id " + getId() + " and balance " + getStan();
}
}
public class Exc7 {
public static void main(String[] args) {
Account account = new Account("0000001"),
acount0 = new Account("0000002", 1000),
acount1 = new Account();
System.out.println(account + "\n" + account0 + "\n" + account1);
}
}
Change return String.valueOf(rand);
To
return String.valueOf(rand.nextInt());
Reason:
You are passing random Object to valueOf method, not the value you need. Call nextInt() method on it to get the desired random value.
Use this code:
Random rand = new Random(7);
return String.valueOf(Math.abs(rand.nextInt()));
Right now you are representing the Random instance.
Instead printing the String representation of the mathematical absolute of the next int of your random will do the trick.
The Math.abs part is important, otherwise you might have negative numbers.
Use
return String.valueOf(rand.nextInt());
otherwise you will get the string representation of the Random object and not of a random int that it can produce.
Can anyone see what is wrong with my code? I get 0 from return of the calculation.
Created a small calculation on second class and pass the result data to main class, then print.
main class
package javaapplication3;
public class JavaApplication3 {
public static void main(String[] args) {
cal bla = new cal();
bla.getRatio();
String dCount = String.valueOf(bla.getRatio());
System.out.print(dCount);
}
}
second class
package javaapplication3;
public class cal {
public int total = 11;
public int count = 2508;
public int calRatio;
public void caln () {
calRatio = count / total;
System.out.print(calRatio);
}
public int getRatio () {
return (calRatio);
}
}
PS: By changing bla.getRatio to bla.caln(); worked. I think I've got other projects mixed up. Thanks for the input guys.
You're doing integer division, which truncates the result to an integer.
You need to cast either operand to double.
bla.getRatio();
String dCount = String.valueOf(bla.getRatio());
You never call the caln()-method, so calRatio is 0 forever.
Maybe you meant the following:
bla.caln();
String dCount = String.valueOf(bla.getRatio());
Plus, you try to divide integers. Try this:
public class cal {
public int total = 11;
public int count = 2508;
public double calRatio;
public void caln () {
calRatio = count / total;
System.out.print(calRatio);
}
public double getRatio () {
return calRatio;
}
}
You never call the "setter" function caln(), so calRatio was never set. So it returns the 0 for calRatio.
replace
public void caln () {
calRatio = count / total;
System.out.print(calRatio);
}
by this
public cal () {
calRatio = count / total;
System.out.print(calRatio);
}
Try this:
public static void main(String[] args) {
cal bla = new cal();
bla.caln();
String dCount = String.valueOf(bla.getRatio());
System.out.print(dCount);
}
I get 0 from return of the calculation.
As you should. 11 / 2508 does an integer division which is 0
If you want a non-zero I suggest changing
public double getAverage () {
return (double) total / count;
}
Normally you divide the total by the count to get the average.
It will return 0, always, because you are returning an int type. The result of your division will always be some floating point value, so you need to store it as such, and return it.
public class cal {
public int total = 11;
public int count = 2508;
public double calRatio;
public void caln() {
calRatio = (double)count / (double)total;
System.out.print(calRatio);
}
}