简体   繁体   中英

How to apply operations on scanner inputs in java?

I have the following code:

import java.util.Scanner;
public class Calculator{
public static void main(String[]args){
    Scanner keyboard = new Scanner(System.in);
    boolean go = true;
    System.out.println("PLEASE ENTER YOUR GRADES");
    double grade = keyboard.nextDouble();
    while (go){
        String next = keyboard.next();
            if (next.equals("done") || next.equals("calculate")){
                System.out.print(grade);
                go = false;
            }else{
                grade+=keyboard.nextInt();
            }
    }

I am trying to find the average as it is a grade calculator, what i want to know is how would I apply The addition operation only to scanner inputs , and then ultimately find the average by how mnay inputs were entered.

Sample input:

60
85
72
done

Output:

72 (average) ===> (217/3)

You need a counter (eg count as shown below). Also, you need to first check the input if it is done or calculate . If yes, exit the program, otherwise parse the input to int and add it to the existing sum ( grade ).

import java.util.Scanner;

public class Calculator {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        boolean go = true;
        System.out.println("PLEASE ENTER YOUR GRADES");
        double grade = 0;
        int count = 0;
        while (go) {
            String next = keyboard.nextLine();
            if (next.equals("done") || next.equals("calculate")) {
                go = false;
            } else {
                grade += Integer.parseInt(next);
                count++;
            }
        }
        System.out.println((int) (grade / count) + " (average) ===> (" + (int) grade + "/" + count + ")");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM