CodingForums.com

CodingForums.com (http://www.codingforums.com/index.php)
-   Java and JSP (http://www.codingforums.com/forumdisplay.php?f=54)
-   -   How to add user input in an array (http://www.codingforums.com/showthread.php?t=283382)

CodyJava 12-02-2012 01:32 AM

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.

zergi 12-02-2012 02:16 PM

In the cycle use the int type for j instead of double.

Quote:

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;
}



All times are GMT +1. The time now is 01:16 AM.

Powered by vBulletin®
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.