英文:
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 = "";
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);
}
}
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] += "*"
Any suggestions?
答案1
得分: 1
asterisk[i] += "*"
这里的 i
是你的数据的索引,表示 f
的索引,但应该是范围的索引,直接像 asterisk[0]
、asterisk[1]
... 这样指定。
if (f[i] >= 1 && f[i] <= 10) {
asterisk[0] += "*";
}
if (f[i] >= 11 && f[i] <= 20) {
asterisk[1] += "*";
}
...
或者你可以为你的条件使用嵌套循环动态处理
```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] += "*";
}
}
}
英文:
asterisk[i] += "*"
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] >= 1 && f[i] <= 10) {
asterisk[0] += "*";
}
if (f[i] >= 11 && f[i] <= 20) {
asterisk[1] += "*";
}
...
Or you can use a nested loop for your condition dynamically
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] += "*";
}
}
}
答案2
得分: 1
我不知道你说的是什么意思
> 如何将数组重置为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<asterisks.length; i++) {
asterisks[i] = "";
}
// 做与你之前的代码完全相同的事情,但使用一个数组
for (int i=0; i<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 "space" of the array
for (int i=0; i<asterisks.length; i++) {
asterisks[i] = "";
}
// do exactly what your code did before, but with an Array
for (int i=0; i<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]);
}
}
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的示例:
- 定义一个函数以生成给定整数值的范围
0_10
、11_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);
}
- 将数组转换为频率映射。
映射可以按不同方式按范围排序:对于这个示例,使用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);
- 实现一个方法以将条目打印为柱状图列:
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
- 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 "previous" range
return String.valueOf((x > 10 ? 1 : 0) + ten) + "_" + String.valueOf(10 + ten);
}
- 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 useTreeMap
.
Arrays.stream(f)
.boxed() // convert IntStream to Stream<Integer> to work with collectors
.collect(Collectors.toMap( // build frequency map as Map<String, Integer>
MyClass::buildRange, x -> 1, Integer::sum, TreeMap::new
))
.entrySet().forEach(MyClass::printEntry);
- Implement the method to print entry as a histogram column:
private static void printEntry(Map.Entry<String, Integer> entry) {
System.out.printf("%5s | %s%n",
entry.getKey(),
String.join("", Collections.nCopies(entry.getValue(), "*"))
// or "*".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 | *
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论