How can i calculate the average in java

how can i calculate the avergae mark out of two marks for instance in like exam mark out
of two other ones
thanks for considering this message

Average or Mean:
sum_of_N/N
Here N is the number of marks.
sum_of_N is the total sum of n(all marks added together)
public int average(int[] marks) {
int sum;
sum = 0;
for(int i=0;i < marks.length;i++) {
sum=marks[i]+sum; // keep adding to the total
return average = sum/marks.length;
// warning- using an int here can be a pitfall(we could have a decimal outcome).
}

Similar Messages

  • HOW can u calculate the average it wont calculate

    import java.util.*;
    public class Percentage
    public static void main (String [] args)
    System.out.println("Enter marks (value < 0 to stop");
    int totalMarks = 0;
    int numberOfMarks = 0;
    Scanner input= new Scanner (System.in);
    int nextMark = input.nextInt();
    while (nextMark >= 0)
    totalMarks += nextMark;
    numberOfMarks++;
    System.out.println("Next mark:");
    nextMark = input.nextInt();
    if ( numberOfMarks > 70)
    int average = (totalMarks/numberOfMarks*100);
    System.out.println (" Average is");
    }

    Compile error!?! You're regressing!
        public static void main(String[] args) {
            System.out.println("Enter marks (value < 0 to stop");
            int totalPassingScores = 0;
            int totalScores = 0;
            Scanner input = new Scanner(System.in);
            double nextMark = input.nextDouble();
            while (nextMark >= 0) {
                totalScores++;
                System.out.println("Next mark:");
                nextMark = input.nextDouble();
                if (nextMark > 70) {
                    totalPassingScores++;
            double percentPassed = (float) totalPassingScores / (float) totalScores * 100.0;
            System.out.println("Number of passing scores: " + percentPassed);
        }

  • How can I calculate the total time in java?

    Hello!
    I need to calculate the total time!
    For example I have start time:
              Format formatter1;
              Date date1 = new Date();
              formatter1 = new SimpleDateFormat("hh:mm:ss");
              String startTime = formatter1.format(date1);
              //startTime = "14:20:40";
    And I have finish time:
              Format formatter2;
              Date date2 = new Date();
              formatter2 = new SimpleDateFormat("hh:mm:ss");
              String finishTime = formatter2.format(date2);
              //finishTime = "08:30:55";
    So, after manually calculating, I get total time: "18:10:15"
    How can I calculate the total time in java? (Using formatter1 and formatter2 I suppose)
    What I need is to print "total 18:10:15"
    Thanks!

    800512 wrote:
    I did the following but, I think something is wrong here:
    I defined before: Date date1 = new Date(); Date date2 = new Date();
    And it should be exactly 5 seconds between them.
    I found delta between date1 and date2:
    Format formatter = new SimpleDateFormat("HH:mm:ss");
              long timeInMilliFromStart = date1.getTime() - date2.getTime() ;
              Date date3 = new Date(timeInMilliFromStart);
              String timeInSecFromStart = formatter.format(date3);
    and I get always
    //timeInSecFromStart = 02:00:05
    But it should be exactly 00:00:05.
    What can be a problem?Because, like I said, a Date measure an instant in time, not a duration. So when you have 5000 ms, and you turn that into a Date, that means 5 sec. after the epoch, which works out to 1/1/1970 00:00:05.000 GMT.
    As I mentioned, if you're not currently in GMT, then you have to set the TZ of the DateFormat to GMT. Right now, it's showing you the time in your TZ. If you included the date in your SimpleDateFormat, you'd see either 1/1/1970 or 12/31/1969, depending on which TZ you're in.
    Bottom line: You're trying to use these classes in a way they're not meant for, and while you can get the results you want for a limited set of inputs if you understand what these classes do and how to work with that, it's a brittle approach and comes with all kinds of caveats.

  • How can I calculate the request time ?

    Hello,
    How can I calculate the total consume time in each request ?
    For example, I want to start calculating the time when I click on a Link or a button and the end time when it completed load the page !
    Eric

    You could use a filter like this one:
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.text.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import javax.servlet.Filter;
    import javax.servlet.FilterChain;
    import javax.servlet.FilterConfig;
    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;
    public class TimeFilter implements Filter {
        // The filter configuration object we are associated with.  If
        // this value is null, this filter instance is not currently
        // configured.
        private FilterConfig filterConfig = null;
        private static final boolean debug = false;
        private long start = 0;
        private long end = 0;
        public TimeFilter() {
        private void doBeforeProcessing(ServletRequest request, ServletResponse response)
        throws IOException, ServletException {
            if (debug) log("CalendarFilter:DoBeforeProcessing");
            System.out.print("In Filter  ");
            this.start = System.currentTimeMillis();
            System.out.println((new java.util.Date()).toString() +
                               " start request ");
        private void doAfterProcessing(ServletRequest request, ServletResponse response)
        throws IOException, ServletException {
            if (debug) log("TimeFilter:DoAfterProcessing");
            System.out.println("Completion Time = " + (System.currentTimeMillis() - start));
         * @param request The servlet request we are processing
         * @param result The servlet response we are creating
         * @param chain The filter chain we are processing
         * @exception IOException if an input/output error occurs
         * @exception ServletException if a servlet error occurs
        public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain)
        throws IOException, ServletException {
            if (debug) log("TimeFilter:doFilter()");
            doBeforeProcessing(request, response);
            Throwable problem = null;
            try {
                chain.doFilter(request, response);
            catch(Throwable t) {
                problem = t;
                t.printStackTrace();
            doAfterProcessing(request, response);
            // If there was a problem, we want to rethrow it if it is
            // a known type, otherwise log it.
            if (problem != null) {
                if (problem instanceof ServletException) throw (ServletException)problem;
                if (problem instanceof IOException) throw (IOException)problem;
                sendProcessingError(problem, response);
         * Return the filter configuration object for this filter.
        public FilterConfig getFilterConfig() {
            return (this.filterConfig);
         * Set the filter configuration object for this filter.
         * @param filterConfig The filter configuration object
        public void setFilterConfig(FilterConfig filterConfig) {
            this.filterConfig = filterConfig;
         * Destroy method for this filter
        public void destroy() {
         * Init method for this filter
        public void init(FilterConfig filterConfig) {
            this.filterConfig = filterConfig;
            if (filterConfig != null) {
                if (debug) {
                    log("TimeFilter:Initializing filter");
         * Return a String representation of this object.
        public String toString() {
            if (filterConfig == null) return ("TimeFilter()");
            StringBuffer sb = new StringBuffer("TimeFilter(");
            sb.append(filterConfig);
            sb.append(")");
            return (sb.toString());
        private void sendProcessingError(Throwable t, ServletResponse response) {
            String stackTrace = getStackTrace(t);
            if(stackTrace != null && !stackTrace.equals("")) {
                try {
                    response.setContentType("text/html");
                    PrintStream ps = new PrintStream(response.getOutputStream());
                    PrintWriter pw = new PrintWriter(ps);
                    pw.print("<html>\n<head>\n</head>\n<body>\n"); //NOI18N
                    // PENDING! Localize this for next official release
                    pw.print("<h1>The resource did not process correctly</h1>\n<pre>\n");
                    pw.print(stackTrace);
                    pw.print("</pre></body>\n</html>"); //NOI18N
                    pw.close();
                    ps.close();
                    response.getOutputStream().close();;
                catch(Exception ex){ }
            else {
                try {
                    PrintStream ps = new PrintStream(response.getOutputStream());
                    t.printStackTrace(ps);
                    ps.close();
                    response.getOutputStream().close();;
                catch(Exception ex){ }
        public static String getStackTrace(Throwable t) {
            String stackTrace = null;
            try {
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                t.printStackTrace(pw);
                pw.close();
                sw.close();
                stackTrace = sw.getBuffer().toString();
            catch(Exception ex) {}
            return stackTrace;
        public void log(String msg) {
            filterConfig.getServletContext().log(msg);
    }and in the web.xml :
       <filter>
            <filter-name>TimeFilter</filter-name>
            <filter-class>
                com.filter.TimeFilter
            </filter>
        <filter-mapping>
            <filter-name>TimeFilter</filter-name>
            <url-pattern>/services/*</url-pattern>
        </filter-mapping > 

  • How do i calculate the average of runs that have variable number of samples?

    Hi
    I am trying to calculate the average trajectory from  lets say 4 runs, with varying sample size.
    That is, if the the 4 runs have 78,74,73,55 samples respectively, How do I calculate the average of (78+74+73+55)/4 , (78+74+73)/3 and (78+74)/2  and 78/1 ?
    Thank you

    I'm not sure you gave a sufficient information. Assuming that you just want to calculate a linear average of the data collected in consecutive runs, you have two simple methods :
    1/ concatenate the data before calculating the mean.
    Simple, but can occupy a huhe amount of space since all the data have to be stored in memory
    2/ store only the means Mi and the corresponding number of data points ni and calculate a balanced mean : M = sum (ni x Mi) / sum (ni) )
    The attached vi illustrate both methods.
    Chilly Charly    (aka CC)
             E-List Master - Kudos glutton - Press the yellow button on the left...        
    Attachments:
    Averages.vi ‏40 KB

  • How can i display the result of java class in InputText ?

    Hi all,
    How can i get the result of java class to InputText Or OutputText ???
    also can every one in the forum give me road map for dealing with java in oracle adf because i'm beginner in oracle adf
    i saw some samples in oracle adf corner but it's difficult for me.

    User,
    Always mention your JDev version, technologies used and clear usecase description (read through this announcement : https://forums.oracle.com/forums/ann.jspa?annID=56)
    How can i get the result of java class to InputText Or OutputText ???Can you elaborate on your requirement? Do you mean the return value of a method in a class as output text? Or an attribute in your class (bean?) as text field?
    -Arun

  • How can I calculate the waveform integral in a defined time interval?

    Hi:
    I need your help. How can I calculate the waveform integral in a defined time interval? For example: from "0" to "2pi"?!
    Thanks.

    Hello Clecio,
    You might want to try the Integral x(t) VI.  The documentation for this VI notes:
    Performs the discrete integration of the sampled signal X. Integral x(t) calculates a definite integral. The value of the output array at any value x is the area under the curve of the input array between 0 and x.
    You would pass the samples of the waveform that fall between your particular window, then pass 1/number of samples for the d(t) parameter.
    Hope that helps.
    Wendy L
    LabWindows/CVI Developer Newsletter - ni.com/cvinews

  • How can i get the average graph?(DIAdem)

    hi,
    How can i get the average graph(2D-graph) of 10 measures?
    Can someone please help me?
    THX!!!

    Hello Charleen!
    If you want to do it programmatically have a look at the ChnAverage command in the help (see also StatBlockCalc for advanced calculations). Interactive you can use the statistic functions in the ANALYSIS device.
    Matthias
    Matthias Alleweldt
    Project Engineer / Projektingenieur
    Twigeater?  

  • How can i open the popup from java class

    Hi,
    Please tell me how can i open the popup from java class.
    I am using jdev 11.1.1.7.0
    I have used the below code which works fine in jdev 2.1 but it will have some errors in 11.1.1.7.0.
    Please tell me some way to do this in all jdev versions.
    Bean obj = (Bean)RequestContext.getCurrentInstance.getExternalContext.getPageFlowScope(“obj”);
    Code for hide pop-up
    FacesContext context = FacesContext.getCurrentInstance();
    String popupId = obj.getPopUpBind().getClientId()
    ExtendedRenderKitService service = Service.getRenderKitService(FacesContext.getCurrentInstance(),
    ExtendedRenderKitService.class);
    String hidePopup = "var popupObj=AdfPage.PAGE.findComponent('" + popupId +
    "'); popupObj.hide();";
    service.addScript(FacesContext.getCurrentInstance(), hidePopup);
    Code to Show pop-up
    StringBuffer showPopup = new StringBuffer();
    showPopup.append("var hints = new Object();");
    showPopup.append("var popupObj=AdfPage.PAGE.findComponent('" +
    obj.getPopUpBind().getClientId() + "');popupObj.show(hints);");
    service.addScript(FacesContext.getCurrentInstance(), showPopup.toString());
    Code need to be added in jsff pop tag
    binding="#{pageFlowScope.bean.popUpBind}
    Variable need to be added in Bean.java
    private RichPopup popUpBind;

    Hari,
    Since you're using a non-public build of JDeveloper, you should be using a non-public forum.
    John

  • How can we position the cursor in Java?

    how can we position the cursor in Java? Please help me.
    and also provide me the list of threading practical question?

    I am talking in context of console.Note that the console can be a number of things in Java; command shell, teletype, etc. You can use either JNI or a third-party library such as jcurses for this sort of thing.
    ~

  • Text on path: How can I calculate the text length?

    Hi
    I have a text on path (spline item). Now I need the length of this text and the length of the spline item.
    I try to calculate the text length using IWaxLine::GetWidth(), but this is always 0.
    - How can I calculate the length of this text?
    - How can I calculate the length of the spline item?
    Thanks
    Hans

    It would be interesting if you could describe the purpose of your "length", but I don't have an answer anyway. Would the bounding box be sufficient?
    Considering that TOP may be combined with arbitrary spline paths, this could become an exercise in higher math. I haven't yet encountered a function that returns the mathematical length of such a spline.
    Otherwise it could be solved if you iterate and sum up the relevant points of the bounding box (ascender, descender, baseline?) of individual glyphs.
    Be warned that the whole TOP looks alien, as if it were a transplant from a different program. Experience also shows that documented and actually used interfaces / commands are completely different animals ...
    Dirk

  • How do I calculate the average of ONLY the populated fields?

    I'm working on an Adobe form to streamline the process of summarizing course evaluations.  To protect the anonymity of the students, instructors with 10 or fewer students are given a typed summary of the evaluation results.  On the first half of the evaluation, the students are asked to rate a series of statements from 1-5.  Three of these are highlighted on the summary form with the average response. 
    I've already set up the form with 10 unique boxes for each question and an 11th box which calculates the average.  Each field is named according to the question number and the student's "number" (I arbitrarily gave each student a number so that each field would be unique):
    i.e. #1. Questionquestionquestion.  Q1S1  Q1S2  Q1S3  Q1S4  Q1S5  Q1S6  Q1S7  Q1S8  Q1S9  Q1S10  1AVG
    The problem, of course, is that no matter how many students were actually in the class, the AVG field will always be calculated based on a group of 10...which isn't accurate or fair to the instructor.  I thought about just changing the form and removing the unused fields from the equation each time I make up a new summary, but the point of creating a form was to make it as quick and easy as possible to bang these things out... Plus, some of my coworkers might be using the form from time to time and I'd have to explain what they have to do and if they don't have Adobe Acrobat then they can't actually make the changes and blah blah blah...it just gets ridiculous really quickly!
    So anyway, I tried reading some other posts for similar questions in an attempt to figure out a custom calculation script for myself, but I just couldn't focus on it.
    I was hoping someone could explain how to write a custom calculation script that will omit any fields which are left blank... Or, even better...is anyone willing to write it for me?  At least just an example of the first guy, cause I could probably figure out how to get all the other ones from there.
    Thanks.

    In formcalc the function Avg will calculate the average of only the fields with a value in them. So you would would put in the calcuate event of the average field:
    $ = Avg(Q1S1,Q1S2,Q1S3,Q1S4, etc)

  • How can I calculate the value of the cell, which depends on other rows?

    Hi, all!
    I have an application with table. In this table i have calculate some fields, that doesn't exists in data class and depends on other row values, e.g. current row number, or sum of previous rows. How can i calculate this values in TableView?
    The problem is that I have no information about the current row number in the cell value factory.
    Example:
    public class Transaction {
         public String getName();
         public BigInteger getAmount();
    } // There is no getter for "Balance"
    Result table should be something like this:
    Name
    Amount
    Balance
    transaction1
    300
    300
    transaction2
    200
    500
    transaction3
    500
    1000
    Also, after sorting by "Amount", "Balance" should be recalculated:
    Name
    Amount
    Balance
    transaction3
    500
    500
    transaction1
    300
    800
    transaction2
    200
    1000

    Strings can be converted to numbers by various parse methods. For instance Strings can be converted to double via Double.parseDouble(myString).
    That being said, it appears that your textfield will contain numbers and operators, and so these operators will need to be parsed too. I would advise you to search on the terms Java infix postfix.

  • How can i calculate the percentile rank?

    How can I calculate where in percentile terms a single value falls within a array of many values?
    In excel it is:
    5
    10
    12
    11
    26
    18
    14
    11
    16
    19
    =PERCENTRANK(A1:A10,10) = 0.111
    Thanks!

    Average or Mean:
    sum_of_N/N
    Here N is the number of marks.
    sum_of_N is the total sum of n(all marks added together)
    public int average(int[] marks) {
    int sum;
    sum = 0;
    for(int i=0;i < marks.length;i++) {
    sum=marks[i]+sum; // keep adding to the total
    return average = sum/marks.length;
    // warning- using an int here can be a pitfall(we could have a decimal outcome).
    }

  • How can I calculate the characters with spaces in a document on pages

    I'm currently using pages to write my personal statement up on, although i need to keep my characters including spaces under 4000 characters and also have no more than 47 lines. I've found how to do a word count and find how many charcaters I've used, but i can't see anywhere the information that I actually need to find! Someone please help, thankyou

    How can you calculate the number of lines if you don't know how many characters there are to a line?
    This is 2013. We are using word processors with real fonts, not terminals or teletypers or typewriters.
    If you must have 47 lines then shrink the point size of the font until it fits.
    Peter

Maybe you are looking for

  • Crystal Report 13 Visual Studio 2010 SQL Server 2008 R2 ODBC Problem

    Hi Everybody, I am new in Crystal Report. I developed a web application in Visual Studio 2010, and my Database is SQL Server 2008 R2. I created reports using Crystal Report 13 in Visual Studio and my Operating System is Windows 7 32-Bit. I used ODBC

  • How to play sound in servlet program

    How to play sound when a page is gernerated? Thank you for any suggestion.

  • Print-out of shopping carts - add additional informations

    Hi SRM-experts, one simple question. Is it possible without modification to add in the print-out of the shopping cart additional informations such as the purchase order number. Is there a possibility to customize that function ? Thanks for yours repl

  • SSIS execute process task error on unziping

    Hi I am using 7zip to unzip files in SSIS using execute process task. Here is the configuration of the task: executable: C:\Program Files\7-Zip\7z.exe arguments: e default-o\\servername\livechat\unzip\ However, on executing package in BIDS, following

  • Clearing document number

    how to find clearing document number if i have purchaseorder number and invoice number???