算出百分比

时间:2019-06-19 20:31:23

标签: java

尝试计算以下代码的百分比, 代码说明:增强的for循环是来自外部mysql数据库的int编号列表。 if语句为从数据库接收到的int分配1、0或-1。

基本上,我想将所有的1加起来并除以for循环中的总数,并显示一个百分比。有人可以帮我这个吗。

     /**
     * Float variable which contains a percentage of positive moods recorded by the user.
     */
    float percentage;

    /**
     * Float Variable which contains the total number of positive moods recorded by the user.
     */
    float total;

    /**
     * Float variable which contains the mood number which is transferred from the MYSQL database.
     */
    float val;


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        // Used for debugging purposed - displays string in the logcat
        Log.d(TAG, "onCreateView: Starting to Create LineChart");

        // Used to get the users ID from the stored shared preferences
        loginPref = getContext().getSharedPreferences("loginPref", Context.MODE_PRIVATE);

        // Displays the layout fragment_mood_log_line_graph.xml file
        View view = inflater.inflate(R.layout.fragment_mood_log_line_graph, container, false);

        // Initialises the pieChart view
        mLineChart = view.findViewById(R.id.lineGraph);

        // Method call to getPieChart();
        getLineGraph();

        moodLogTitle1 = view.findViewById(R.id.moodLogTitle);
        moodLogTitle1.setText("moodlog"+percentage);

        // Initialises all of the above on screen.
        return view;

    }


    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

    }

    /**
     * Method whichs contains the linegraph
     */
    private void getLineGraph() {

        // Used for debugging purposes.
        Log.d(TAG, "getLineChart: GetLineChart Method");

        // Declare the userID which is obtained from the shared preferences.
        final int userId = loginPref.getInt("userId", 0);

        // Retrofit call to the MYSQL server.
        Call<List<MoodLogLineGraph>> call = RetrofitClient.getInstance().getApi().moodLogLineGraph(userId);
        call.enqueue(new Callback<List<MoodLogLineGraph>>() {
            @Override
            public void onResponse(Call<List<MoodLogLineGraph>> call, Response<List<MoodLogLineGraph>> response) {

                // All JSON entries form the MYSQL server are parsed into an ArrayList.
                ArrayList<Entry> yVals = new ArrayList<Entry>();


                // For loop which dynamically adds all entries to the ArrayList
                // response.body() contains the JSON parsed from the database. The JSON
                // contains all the information requested from the database such as moodId,
                // moodName, posted(date) etc.
                // Getters are used to select specific pieces of information form the JSON array.
                for (MoodLogLineGraph moodLogList : response.body()) {

                    // The getter .getMoodBefore contains an int between 1-11. These ints represent
                    // the mood the user has inputted to the database i.e 1=happy, 11= Depressed etc.
                    // The float val is used to store the integer so it can used in a LineGraph.
                    val = (float) moodLogList.getMoodBefore();

                    // The ints 1-11 which are received form the MYSQL database are then
                    // manually assigned a 1, 0 or -1.
                    // 1 = positive mood.
                    // 0 = Neutral mood.
                    // -1 = Negative mood.
                    // These values are then uses to plot a simple LineGraph showing increases and
                    // decreases in the users mood.

                    if ((moodLogList.getMoodBefore() == 1) || (moodLogList.getMoodBefore() == 2) || (moodLogList.getMoodBefore() == 3) || (moodLogList.getMoodBefore() == 4) ) {
                        // If the JSON contains a 1-4 it is assigned the value 1 which represents
                        // a positive mood on the LineGraph
                        val = 1;
                        // If a positive mood is recorded 1 is added to the total variable. 
                        total++;
                    }
                    if ((moodLogList.getMoodBefore() == 8) || (moodLogList.getMoodBefore() == 9) || (moodLogList.getMoodBefore() == 10) || (moodLogList.getMoodBefore() == 5)  ) {
                        // If the JSON contains an 5, 8. 9, or 10  it is assigned the value 0 which represents
                        // a neutral mood on the LineGraph
                        val = 0;
                    }
                    if ((moodLogList.getMoodBefore() == 6) || (moodLogList.getMoodBefore() == 7) || (moodLogList.getMoodBefore() == 11)  ) {
                        // If the JSON contains an 6, 7. or 11  it is assigned the value -1 which represents
                        // a negative mood on the LineGraph
                        val = -1;
                    }

                    // Takes the total of positive moods i.e. 1's and divides them by the entire list received
                    // from the MYSQL database to work out a percentage total of positive moods.
                     percentage = total / response.body().size();


                    // Obtains the date the mood was recorded from the MYSQL database.
                    float date = (float) moodLogList.getDay();

                    // Adds the values and dates to the LineGraph ArrayList.
                    yVals.add(new Entry(date, val));

                }



** Just to be clear the response.body() is the MYSQL JSON which is a long list of ints ranging from 1-11.

These ints are assigned a value of 1. 0 or -1 for the purpose of a linegraph. Thats why theres 11 if statements, assigning each int from the MYSQL to a 1, 0 or -1.

I need to total all the ints from the respnse.body() aka the mysql list and work out how many of them have a 1 value. Then display this value as a percentage.

1 个答案:

答案 0 :(得分:1)

更改了代码以反映我相信您的发言。 response.body()并非总是 一个数字,而是为您提供了不正确的百分比。

    int totalInts = 0;
    int positiveMoods = 0;
    ArrayList<Entry> yVals = new ArrayList<Entry>();

    for (MoodLogLineGraph moodLogList : response.body()) {

    // Obtains the date the mood was recorded from the MYSQL database.
    float date = (float) moodLogList.getDay();


        if (moodLogList.getMoodBefore() >= 1 && moodLogList.getMoodBefore() <= 11)
        {
            totalInts++;
            if (moodLogList.getMoodBefore() >= 1 && moodLogList.getMoodBefore() <= 4)
            {
                 yVals.add(date, 1);
                 positiveMoods++;
            }
            if (moodLogList.getMoodBefore() == 6 || moodLogList.getMoodBefore() == 7 || moodLogList.getMoodBefore() == 11)
                  yVals.add(date, -1);
            if (moodLogList.getMoodBefore() == 5 || (moodLogList.getMoodBefore() => 8 && moodLogList.getMoodBefore() <= 10))
                  yVals.add(date, 0);
        }
   float percentage = positiveMoods / totalInts;