Results 1 to 4 of 4

Thread: Need some help

  1. #1
    garrett2smart is offline New To Java
    Join Date
    Jun 2012
    Posts
    3
    Rep Power
    0

    Default Need some help

    Hey there, I am extremely new to java and was wanting some help on this bug I am getting.
    My code is as follows:
    Java Code:
    import java.util.Scanner;
    public class bavg{
    	public static void main (String args[]){
    		Scanner keyboard=new Scanner(System.in);
    		System.out.println("Enter the amount of at-bats.");
    		int ab=keyboard.nextInt();
    		System.out.println("Now, enter the amount of hits.");
    		int hits=keyboard.nextInt();
    		double avg=(hits/ab);
    		System.out.println("Your batting average is "+avg+".");
    	}
    }
    But whenever I run the program, no matter what I do, I get my average is 0.0
    Anyone have any suggestions?

    Again I am very new to java so I apologize in advance for any silly mistakes.

  2. #2
    garrett2smart is offline New To Java
    Join Date
    Jun 2012
    Posts
    3
    Rep Power
    0

    Default Re: Need some help

    I tried turning the int "avg" into a double to see if that did anything, but it didn't help.

  3. #3
    atac57 is offline Member
    Join Date
    Jan 2012
    Posts
    24
    Rep Power
    0

    Default Re: Need some help

    You need to type cast the int variables to double. If "ave" is a double, "ab" and "hits" need to be converted into doubles as well.

    Java Code:
    double avg= (double)hits/(double)ab;
    Or this, basically the same thing:
    Java Code:
    double avg= ((double)hits)/ab;
    Alternatively, you could just change those int variables into double.
    Last edited by atac57; 06-12-2012 at 03:04 AM.

  4. #4
    garrett2smart is offline New To Java
    Join Date
    Jun 2012
    Posts
    3
    Rep Power
    0

    Default Re: Need some help

    Quote Originally Posted by atac57 View Post
    You need to type cast the int variables to double. If "ave" is a double, "ab" and "hits" need to be converted into doubles as well.

    Java Code:
    double avg= (double)hits/(double)ab;
    Or this, basically the same thing:
    Java Code:
    double avg= ((double)hits)/ab;
    Alternatively, you could just change those int variables into double.
    Thanks so much it works great now!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •