0

Can anyone tell me what the problem with my code here?? It is a simple java program that calculate the sum of 2 rational numbers

import java.util.Scanner; public class Exercise5 { static public void main(String[] args){ Scanner input = new Scanner(System.in); int a, x, b, y; double result=0; System.out.print("Please enter the numerator for the 1st rational number: "); a = input.nextInt(); System.out.print("Please enter the demonator for the 1st rational number: "); x = input.nextInt(); System.out.print("Please enter the numerator for the 1nd rational number: "); b = input.nextInt(); System.out.print("Please enter the demonator for the 1nd rational number: "); y = input.nextInt(); if (x==0 || y==0){ System.out.println("invalid input as the demonator cannot be Zero"); } else { result = ((a*y)+(b*x))/(x*y); System.out.printf("the result is: ",result); } input.close(); } }

18th Sep 2021, 6:49 AM
Maryam Magdy
Maryam Magdy - avatar
6 Respostas
+ 2
Maryam Magdy , the output you have tried with printf() needs to have a placeholder: System.out.printf("the result is: %d", result); // %d => integer, %f =>float ^
18th Sep 2021, 9:01 AM
Lothar
Lothar - avatar
+ 1
This is happening becz you have taken variable int type and if you will perform operations on int data type it will give you int result am i right and you assigning int result to your result variable that's why it printing with 3.0 .... In this case you need to do casting with double data type in expression then you will get proper output try this.
18th Sep 2021, 7:07 AM
A S Raghuvanshi
A S Raghuvanshi - avatar
+ 1
Thanks A.S. That's right I changed the types for the variables into double and it works!!
18th Sep 2021, 7:13 AM
Maryam Magdy
Maryam Magdy - avatar
+ 1
18th Sep 2021, 7:19 AM
A S Raghuvanshi
A S Raghuvanshi - avatar
0
i think so you are confused with python and java i should be System.out.println("the result is: " + result); not System.out.printf("the result is: ",result); in java we use ' + ' plus operator not ' , ' comma
18th Sep 2021, 6:53 AM
Pariket Thakur
Pariket Thakur - avatar
0
Thank you HrCoder i edited it but the result is not correct i tried for two number the result should be 4.6 but the program displays it as 4.0
18th Sep 2021, 6:57 AM
Maryam Magdy
Maryam Magdy - avatar