Java 列出百分比

Java 列出百分比,java,Java,试图计算出下面代码的百分比, 代码解释:增强的for循环是来自外部mysql数据库的整数列表。if语句将1、0或-1分配给从数据库接收的int 基本上我想把所有的1加起来,除以for循环中的总数,然后显示一个百分比。有人能帮我做这个吗 /** * Float variable which contains a percentage of positive moods recorded by the user. */ float percentage;

试图计算出下面代码的百分比, 代码解释:增强的for循环是来自外部mysql数据库的整数列表。if语句将1、0或-1分配给从数据库接收的int

基本上我想把所有的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.


更改代码以反映我相信您所说的内容。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;

你有什么问题吗?为什么你不能把1加起来,然后除以总数呢?我也不明白你为什么要用这么多if语句。10和-1是从哪里来的?有没有一个函数可以代替这么多的if语句?你能添加更多的代码吗?val的用途是什么?因为设置val=0的值对平均值没有影响,所以您可以省略那些if语句,不管值为0有多重要,它们的原始值都是从1-11 Im手动分配给它们一个1,0或-1表示折线图,但如果正文是集合,则它们仍然需要合计或.size。这不起作用。我添加了更多的代码和对原始问题的解释。