问题
HISTOGRAM:
I have problem in my code..
The Intended Output must be something Like this:
Output:
0 8 ********
1 6 ******
2 3 ***
3 7 *******
But mine shows:
0 8 *******************************
1 6 *******************************
2 3 *******************************
3 7 *******************************
I've searched and compare it to my code but nothing really helps me though..
Can you kindly take a look at my code and give some suggestions, and comments on
how could I code the intended output properly..
Any Help is Appreciated ...
public static void main(String args[]) {
{
StringBuilder stringBuilder = new StringBuilder();
int n = 0;
n = Integer.parseInt(JOptionPane.showInputDialog("Enter value"));
int[] arr = new int[n];
String stars = "";
int input = 0;
for(int c = 0; c<n; c++ ){
input = Integer.parseInt(JOptionPane.showInputDialog("Enter number"));
arr[c]=input;
for(int i=0; i<input; i++){
stringBuilder.append("*");
}
}
for(int i=0; i<input; i++){
stringBuilder.append("*");
}
for (int o = 0; o<n ; o++){
stars = stringBuilder.toString();
System.out.println( o +" "+arr[o]+" "+stars);
}
}
}
}
回答1:
Every time you append the *
in the builder object, clear the previous content. You can use stringBuilder.setLength(0)
;
import javax.swing.*;
public class Prop {
public static void main(String args[]) {
StringBuilder stringBuilder = new StringBuilder();
int n = 0;
n = Integer.parseInt(JOptionPane.showInputDialog("Enter value"));
int[] arr = new int[n];
String stars = "";
int input = 0;
for(int c = 0; c<n; c++ ){
input = Integer.parseInt(JOptionPane.showInputDialog("Enter number"));
arr[c]=input;
for(int i=0; i<input; i++){
stringBuilder.append("*");
}
stars = stringBuilder.toString();
System.out.println( c +" "+arr[c]+" "+stars);
stringBuilder.setLength(0); // Reset the `stringBuilder` once pattern is written
}
}
}
Output:
0 8 ********
1 6 ******
2 3 ***
3 7 *******
来源:https://stackoverflow.com/questions/33029885/histogram-array-stars-output