Skip to content
WJunction - Webmaster Forum

[java] Output a Two Decimal Value

Status
Not open for further replies.
I wanted display the result with two decimal values? (12.50) but it seems to be displaying 0 instead of 12.50.

Code:
    import java.io.*;
    
    public class InputOutput {
    	public static void main(String[] args) {
    		String base="";
    		String height="";
    		
    		BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
    		try {
    			System.out.print("Input base value = ");
    			base = input.readLine();
    			System.out.print("Input height value = ");
    			height = input.readLine();
    		} catch(IOException e) {
    			System.out.print("Error");
    		}
    		
    		int area = 1/2*(Integer.parseInt(base)* Integer.parseInt(height));
		System.out.println("The Area of the right triangle is "+ area);
    	}
    }
 
Last edited:

4 comments

make the following changes

Code:
 import java.io.*;
    
    public class InputOutput {
        public static void main(String[] args) {
            double base=0;
            double height=0;
            
            BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
            try {
                System.out.print("Input base value = ");
                base = Double.parseDouble(input.readLine());
                System.out.print("Input height value = ");
                height = Double.parseDouble(input.readLine());
            } catch(IOException e) {
                System.out.print("Error");
            }
            
            double area = 0.5*(base* height);
        System.out.println("The Area of the right triangle is "+ area);
        }
    }
 
^The output was:

Code:
The Area of the right triangle is 0.0
What's wrong?

This is a good time just to think. Your equation is right, so obviously one of the terms is 0. So it would lead to you parsing/casting incorrectly. As 18folder pointed out you cast base and height as integers and you should have casted them as doubles.
 
Status
Not open for further replies.

About the author

H
Active Member · Joined
I am Hillsid3. I consider myself as extraordinary - and we are unique in our own ways. listening to music, watching...
1,535
Messages
13
Reactions
38
Points

Advertise on WJunction

Reach 1000's of webmasters, hosts & affiliates. Banner & sponsored-thread slots available.

Contact us
Back
Top Bottom