如何在每个 if 语句之后重置数组?

huangapple go评论63阅读模式
英文:

How to reset an array after each if statement?

问题

我有这个Java程序正在编写,用户输入20个数字,然后将其存储在数组中。然后打印一个直方图,显示数字被输入的次数:

1-10 |*********

11-20 |*****

21-30 |**

31-40 |**

41-50 |**

这是我的代码:

    String asterisk1 = "";
    String asterisk2 = "";
    String asterisk3 = "";
    String asterisk4 = "";
    String asterisk5 = "";
    System.out.println("Histogram: ");
    System.out.println(" ");
    for (int i = 0; i <= f.length-1; i++)
    {
       
      
        if (f[i] >= 1 && f[i] <= 10)
        {
            asterisk1 += "*";
        }
        if (f[i] >= 11 && f[i] <= 20)
        {
            asterisk2 += "*";
        }
        if (f[i] >= 21 && f[i] <= 30)
        {
            asterisk3 += "*";
        }
        if (f[i] >= 31 && f[i] <= 40)
        {
            asterisk4 += "*";
        }
        if (f[i] >= 41 && f[i] <= 50)
        {
            asterisk5 += "*";
        }
    }
   
    System.out.println(" 1-10 |"+ asterisk1);
    System.out.println("11-20 |"+ asterisk2);
    System.out.println("21-30 |"+ asterisk3);
    System.out.println("31-40 |"+ asterisk4);
    System.out.println("41-50 |"+ asterisk5);
}

所以,我尝试创建一个数组来代替声明每个变量。但问题是,我不知道如何将数组重置为0,以便获取正确数量的星号。我尝试只是执行 String asterisk [] = new String[50];,然后在if循环中只是执行 asterisk[i] += "*"。有什么建议吗?

英文:

I have this Java Program that I am writing where the user inputs 20 numbers and it gets stored in an array. Then you print an histogram that says how many times a number was inputted:

1-10 |*********

11-20 |*****

21-30 |**

31-40 |**

41-50 |**

This is my code:

 String asterisk1 = &quot;&quot;;
String asterisk2 = &quot;&quot;;
String asterisk3 = &quot;&quot;;
String asterisk4 = &quot;&quot;;
String asterisk5 = &quot;&quot;;
System.out.println(&quot;Histogram: &quot;);
System.out.println(&quot; &quot;);
for (int i = 0; i &lt;= f.length-1; i++)
{
if (f[i] &gt;= 1 &amp;&amp; f[i] &lt;= 10)
{
asterisk1 += &quot;*&quot;;
}
if (f[i] &gt;= 11 &amp;&amp; f[i] &lt;= 20)
{
asterisk2 += &quot;*&quot;;
}
if (f[i] &gt;= 21 &amp;&amp; f[i] &lt;= 30)
{
asterisk3 += &quot;*&quot;;
}
if (f[i] &gt;= 31 &amp;&amp; f[i] &lt;= 40)
{
asterisk4 += &quot;*&quot;;
}
if (f[i] &gt;= 41 &amp;&amp; f[i] &lt;= 50)
{
asterisk5 += &quot;*&quot;;
}
}
System.out.println(&quot; 1-10 |&quot;+ asterisk1);
System.out.println(&quot;11-20 |&quot;+ asterisk2);
System.out.println(&quot;21-30 |&quot;+ asterisk3);
System.out.println(&quot;31-40 |&quot;+ asterisk4);
System.out.println(&quot;41-50 |&quot;+ asterisk5);
}
}

So instead of declaring every variable I tried creating an array. But the problem is I am confused how to reset the array to 0 so I get the correct amount of asterisks. I tried to just do String asterisk [] = new String[50]; and in the if loops I would just do asterisk[i] += &quot;*&quot;Any suggestions?

答案1

得分: 1

asterisk[i] += "&ast;" 这里的 i 是你的数据的索引,表示 f 的索引,但应该是范围的索引,直接像 asterisk[0]asterisk[1]... 这样指定。

if (f[i] >= 1 && f[i] <= 10) {
    asterisk[0] += "&ast;";
}
if (f[i] >= 11 && f[i] <= 20) {
    asterisk[1] += "&ast;";
}
...

或者你可以为你的条件使用嵌套循环动态处理

```cpp
for (int i = 0; i <= f.length-1; i++) {
     for(int j = 0; j < 5; j++) {
         if (f[i] >= (j*10 +1) && f[i] <= (j+1)*10) {
             asterisk[j] += "&ast;";
         }
     }
}
英文:

asterisk[i] += &quot;*&quot; here i is the index of your data means f's index but it should be the index of the range, specify directly like asterisk[0], asterisk[1]...

 if (f[i] &gt;= 1 &amp;&amp; f[i] &lt;= 10) {
asterisk[0] += &quot;*&quot;;
}
if (f[i] &gt;= 11 &amp;&amp; f[i] &lt;= 20) {
asterisk[1] += &quot;*&quot;;
}
...

Or you can use a nested loop for your condition dynamically

for (int i = 0; i &lt;= f.length-1; i++) {
for(int j = 0; j &lt; 5; j++) {
if (f[i] &gt;= (j*10 +1) &amp;&amp; f[i] &lt;= (j+1)*10) {
asterisk[j] += &quot;*&quot;;
}
}
}

答案2

得分: 1

我不知道你说的是什么意思

&gt; 如何将数组重置为0

但是我做了一个小例子演示了如果你使用字符串数组而不是五个变量你的程序会是什么样子

    public class HelloWorld {

         public static void main(String []args){
             String[] asterisks = new String[5];  // 在这里设置你想要的大小
             int[] f = { 0, 40, 52, 12, 31, 12, 42, 23, 5, 13, 42, 45, 25, 26, 27, };

            // 初始化数组的每个“空间”
            for (int i=0; i&lt;asterisks.length; i++) {
                asterisks[i] = "";
            }

            // 做与你之前的代码完全相同的事情,但使用一个数组
            for (int i=0; i&lt;f.length; i++) {
                if (f[i] >= 1 && f[i] <= 10) {
                    asterisks[0] += "*";
                } else if (f[i] >= 11 && f[i] <= 20) {
                    asterisks[1] += "*";
                } else if (f[i] >= 21 && f[i] <= 30) {
                    asterisks[2] += "*";
                } else if (f[i] >= 31 && f[i] <= 40) {
                    asterisks[3] += "*";
                } else if (f[i] >= 41 && f[i] <= 50) {
                    asterisks[4] += "*";
                }
            }

            System.out.println(" 1-10 |"+ asterisks[0]);
            System.out.println("11-20 |"+ asterisks[1]);
            System.out.println("21-30 |"+ asterisks[2]);
            System.out.println("31-40 |"+ asterisks[3]);
            System.out.println("41-50 |"+ asterisks[4]);

        }
    }

也许你想使用哈希表使其更具动态性我的意思是你可能不知道你的直方图会有多少列所以你可以创建一个哈希表将一个范围值"21-30""31-40""41-50"与字符串数组上的一个位置关联起来如果你决定采纳我的建议你就不能做最后一个"System.out.println"你应该首先遍历哈希表的每个键然后将对应于每个哈希键的字符串数组位置进行println

如果我在写这个过程中犯了错误我感到很抱歉英语不是我的母语
我希望我的例子对你理解数组的工作方式有所帮助
英文:

I don't know what do you mean when you said

> how to reset the array to 0

But here I made a little example of what your program would like if you use a String array instead of five variables:

public class HelloWorld {
public static void main(String []args){
String[] asterisks = new String[5];  // set the size you want here
int[] f = { 0, 40, 52, 12, 31, 12, 42, 23, 5, 13, 42, 45, 25, 26, 27, };
// initialize every &quot;space&quot; of the array
for (int i=0; i&lt;asterisks.length; i++) {
asterisks[i] = &quot;&quot;;
}
// do exactly what your code did before, but with an Array
for (int i=0; i&lt;f.length; i++) {
if (f[i] &gt;= 1 &amp;&amp; f[i] &lt;= 10) {
asterisks[0] += &quot;*&quot;;
} else if (f[i] &gt;= 11 &amp;&amp; f[i] &lt;= 20) {
asterisks[1] += &quot;*&quot;;
} else if (f[i] &gt;= 21 &amp;&amp; f[i] &lt;= 30) {
asterisks[2] += &quot;*&quot;;
} else if (f[i] &gt;= 31 &amp;&amp; f[i] &lt;= 40) {
asterisks[3] += &quot;*&quot;;
} else if (f[i] &gt;= 41 &amp;&amp; f[i] &lt;= 50) {
asterisks[4] += &quot;*&quot;;
}
}
System.out.println(&quot; 1-10 |&quot;+ asterisks[0]);
System.out.println(&quot;11-20 |&quot;+ asterisks[1]);
System.out.println(&quot;21-30 |&quot;+ asterisks[2]);
System.out.println(&quot;31-40 |&quot;+ asterisks[3]);
System.out.println(&quot;41-50 |&quot;+ asterisks[4]);
}
}

Maybe you would like to use a Hash to make it more dynamic, I mean: probably you will not know how many columns your histogram will have, so you could make a Hash that relate a range value ("21-30", "31-40", "41-50", etc...) to a position on the String Array. If you decide to follow my advice you couldn't do the last "System.out.println", you should for each the Hash keys first, and then println the String Array position correlated to every Hash key.

Sorry if I made mistakes writing this, English is not my native language.
I hope my example has been useful to you to understand how Arrays works.

答案3

得分: 1

使用流式API的示例:

  1. 定义一个函数以生成给定整数值的范围 0_1011_20 等:
private static String buildRange(int x) {
    int ten = (x - 1) / 10 * 10; // 修正以包括 10 的倍数到“前一个”范围
    return String.valueOf((x > 10 ? 1 : 0) + ten) + "_" + String.valueOf(10 + ten);
}
  1. 将数组转换为频率映射。
    映射可以按不同方式按范围排序:对于这个示例,使用 TreeMap 是可以的。
Arrays.stream(f)
      .boxed() // 将 IntStream 转换为 Stream<Integer> 以便使用收集器
      .collect(Collectors.toMap( // 构建频率映射,类型为 Map<String, Integer>
              MyClass::buildRange, x -> 1, Integer::sum, TreeMap::new
      ))
      .entrySet().forEach(MyClass::printEntry);
  1. 实现一个方法以将条目打印为柱状图列:
private static void printEntry(Map.Entry<String, Integer> entry) {
    System.out.printf("%5s | %s%n", 
            entry.getKey(), 
            String.join("", Collections.nCopies(entry.getValue(), "*"))
            // 或 JDK 11+ 可以使用 "*".repeat(entry.getValue())
    );
}

输出
对于输入 int[] f = { 0, 40, 52, 12, 31, 12, 42, 23, 5, 13, 42, 45, 25, 26, 27, };

 0_10 | **
11_20 | ***
21_30 | ****
31_40 | **
41_50 | ***
51_60 | *
英文:

Example of using Stream API:

  • map each element of array to a certain range
  • group the elements by their ranges and count the frequency of each element in the array
  • build a histogram column containing appropriate number of asterisks
  1. Define a function to generate a range 0_10, 11_20, etc. for the given integer value:
private static String buildRange(int x) {
    int ten = (x - 1) / 10 * 10; // correction to include multiple of 10 to &quot;previous&quot; range 
    return String.valueOf((x &gt; 10 ? 1 : 0) + ten) + &quot;_&quot; + String.valueOf(10 + ten);
}
  1. Convert the array into the frequency map.<br/>
    The map may be sorted by ranges in different ways: for this example it's ok to use TreeMap.
Arrays.stream(f)
      .boxed() // convert IntStream to Stream&lt;Integer&gt; to work with collectors
      .collect(Collectors.toMap( // build frequency map as Map&lt;String, Integer&gt;
              MyClass::buildRange, x -&gt; 1, Integer::sum, TreeMap::new
      ))
      .entrySet().forEach(MyClass::printEntry);
  1. Implement the method to print entry as a histogram column:
private static void printEntry(Map.Entry&lt;String, Integer&gt; entry) {
    System.out.printf(&quot;%5s | %s%n&quot;, 
            entry.getKey(), 
            String.join(&quot;&quot;, Collections.nCopies(entry.getValue(), &quot;*&quot;)) 
            // or &quot;*&quot;.repeat(entry.getValue()) for JDK 11+
    );
}

Output<br/>
For the input int[] f = { 0, 40, 52, 12, 31, 12, 42, 23, 5, 13, 42, 45, 25, 26, 27, };

 0_10 | **
11_20 | ***
21_30 | ****
31_40 | **
41_50 | ***
51_60 | *

huangapple
  • 本文由 发表于 2020年10月4日 23:41:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/64196666.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定