Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New Coder
    Join Date
    Sep 2012
    Posts
    32
    Thanks
    25
    Thanked 0 Times in 0 Posts

    How to add user input in an array

    Hey I'm trying to have the user input a value and store it in an array. The only problem is it's saying I can't do it due to a lack of percision (double to int). I've looked and all my values are double. Am I doing it wrong. Thanks.



    Code:
    import java.util.Scanner;
    public class RainfallTester {
        public static void main(String [] args){
        Scanner scan = new Scanner(System.in);
        Rainfall temp = new Rainfall();
        double rain;
        
        for(double j=0; j<temp.rainfall.length;j++ ){
        System.out.println("What is the total rainfall for the month:");
        temp.rainfall[j] = scan.nextDouble(); //this is giving me an error
            }
        System.out.println("The total rainfall for the year is "+temp.getTotal());
        
        System.out.println("The average monthly rainfall is "+temp.getAvg());
        
        System.out.println("The month with the most rainfall is "+temp.getMax());
                
        System.out.println("The month with the least rainfall is "+temp.getMin());
          }
        
    }
    Another question is how would I get values back such as the total do I use counter or something.

    Code:
    public class Rainfall {
        double avgRain;
        double sum = 0;
        
        double rainfall[] = new double[11];
        
         double getTotal(){
             
           return  sum += rainfall[];
         }
         
         double getAvg(){
             sum += rainfall[];
             return sum/rainfall.length;
         }
         
         double getMax(){
             
         }
         
         double getMin(){
             
         }
        
    }
    Thanks.

  • #2
    New to the CF scene
    Join Date
    Nov 2012
    Posts
    9
    Thanks
    1
    Thanked 2 Times in 2 Posts
    In the cycle use the int type for j instead of double.

    Another question is how would I get values back such as the total do I use counter or something.
    Yes, you may use counter
    Code:
    double getTotal(){
      sum = 0;    
      for ( int i = 0; i <  rainfall.length; i++ ) {
        sum += rainfall[i];
      }      
      return  sum; 
    }

  • Users who have thanked zergi for this post:

    CodyJava (12-02-2012)


  •  

    Posting Permissions

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