![](/img/trans.png)
[英]Im trying to make a "graphic" printing a certain amount of characters based on array values java
[英]Hi, trying to print a certain amount of character based on array values. Java
所以我的問題是如何根據數組值打印一定數量的字符?
所以目前我有一個這樣全局聲明的數組
static float timesOccured [] = {5,3,7,3,1};
在一種名為draw的方法中,我嘗試了一些嘗試來獲取它,因此輸出將像這樣
|||||
|||
|||||||
|||
|
有人可以幫我嗎? 非常感激。
您將需要使用嵌套的for循環,如下所示:
for (int i = 0; i < timesOccured.length; i++) {
for (int j = 0; j < timesOccured[i]; j++) {
// print characters here
}
}
遍歷timesOccured
數組並獲取每個條目; 並使用條目(即timesOccured[i]
)在嵌套的for循環中打印行。
我希望這有幫助。
public class PrintChar {
static float timesOccured [] = {5,3,7,3,1};
public static void draw(){
for(int i=0; i<timesOccured.length;i++){
for(int j=0; j< timesOccured[i]; j++){
System.out.print("!");
}
System.out.println();
}
}
public static void main(String[] args) {
draw();
}
}
這有七種方法:
import org.apache.commons.lang.StringUtils;
import com.google.common.base.Strings;
public class StringRepeat {
static int timesOccured[] = { 5, 3, 7, 3, 1 };
static String s = "|";
static String t = "||||||||||||||||||";
public static String repeat(int j) {
return (t.substring(0, j));
}
public static void main(String[] args) {
System.out.println("Using native Java String.substring");
for (int i = 0; i < timesOccured.length; i++) {
System.out.println(repeat(timesOccured[i]));
}
System.out.println("\nUsing native Java char.replace");
for (int i = 0; i < timesOccured.length; i++) {
System.out.println(new String(new char[timesOccured[i]]).replace("\0", s));
}
System.out.println("\nUsing native Java String.format.replace");
String result = "";
for (int i = 0; i < timesOccured.length; i++) {
System.out.println(String.format(String.format("%%0%dd", timesOccured[i]), 0).replace("0",s));
}
System.out.println(result);
System.out.println("\nUsing native Java StringBuilder.append");
for (int i = 0; i < timesOccured.length; i++) {
StringBuilder sb = new StringBuilder();
for (int j = 0; j < timesOccured[i]; j++) { sb.append(s); };
System.out.println(sb.toString());
}
System.out.println("\nUsing native Jave double for loops");
for (int i = 0; i < timesOccured.length; i++) {
String u = "";
for (int j = 0; j < timesOccured[i]; j++) {
u = u + s;
}
System.out.println(u);
}
System.out.println("\nUsing org.apache.commons.lang.StringUtils.repeat");
for (int i = 0; i < timesOccured.length; i++) {
System.out.println(StringUtils.repeat(s, timesOccured[i]));
}
System.out.println("\nUsing com.google.common.base.Strings.repeat");
for (int i = 0; i < timesOccured.length; i++) {
System.out.println(Strings.repeat(s, timesOccured[i]));
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.