在 Java 中,如何根据余数、百分比或浮点值循环某些内容/运行迭代?

问题描述 投票:0回答:1

我的作业要求我采用不同整数形式的数据集,并通过一种方法运行它们,该方法将打印适当数量的字符以创建水平条形图。 该图需要使用由块元素(█、▏、▌)组成的字符串。这些块以 8 为基数,因此输入 8 作为整数应打印“█”,而 16 应打印“██”。 我找到了一种方法来打印可被 8 整除的输入的正确块数,但我不确定如何处理不均匀除法的余数或小数值,例如,如果 (9 / 8) = 1.125 ,我该如何使用0.125?

这是我到目前为止所拥有的,它打印 8 的倍数的适当字符数。

   public static String getHorizontal(int value)
   {

     String bar = "";
     double realMath = (double) value / 8; // (1/8) = (0.125) (8/8) = 1
     int rmConversion;

     while(realMath % 1 == 0){
       rmConversion = (int)realMath;
       for(int i = 0; i < rmConversion; i++){
         bar += "█";
       }
       return bar;
     }
  
    
     //TODO: replace this with code that actually generates the bar graph!
        
     return bar;
     }

如何运行类似的循环但具有余数或小数点值?

java loops floating-point computer-science fractions
1个回答
0
投票

试试这个:

  • 除以 8 计算所需的完整块数。
  • 将该数字加 1,为部分块保留空间。
  • 创建一个在上一步中确定的长度的数组,并填充完整的块字符。
  • 使用
    %
    运算符计算余数,这将给出部分块的大小。
  • 将填充数组中的最后一个字符替换为空格或部分块,具体取决于余数计算的结果。
 public static String bar (int value) {
        final char FULL_BLOCK = '█';
        char [] partBlock = {' ','▏','▎','▍','▌','▋','▊','▉' };
        char [] theBar = new char [value / 8 + 1];
        Arrays.fill (theBar, FULL_BLOCK);
        theBar [theBar.length - 1] = partBlock [value % 8];
        return new String (theBar);
    }
   
    public static void main(String[] args) {
        System.out.println ("Growing Bar:");
        for (int i = 0; i <= 24; ++i) {
            System.out.println (bar (i));
        }

测试:

Growing Bar:
 
▏
▎
▍
▌
▋
▊
▉
█ 
█▏
█▎
█▍
█▌
█▋
█▊
█▉
██ 
██▏
██▎
██▍
██▌
██▋
██▊
██▉
███
© www.soinside.com 2019 - 2024. All rights reserved.