我的輸出應該是這樣的:
1星號(*)
3星級(***)
4星級(****)是否可以增加Java中的字符串或字符?
,比如我有代碼:
char array[] = new char[3];
char x = '*';
For (int i= 0; i < array.length; i++)
{
array[i]='*'
x = x+2;
system.out.println(array[i]);
}
我的輸出應該是這樣的:
1星號(*)
3星級(***)
4星級(****)是否可以增加Java中的字符串或字符?
,比如我有代碼:
char array[] = new char[3];
char x = '*';
For (int i= 0; i < array.length; i++)
{
array[i]='*'
x = x+2;
system.out.println(array[i]);
}
不,這不可能在char[]
數組,你應該做的像,
String array[] = new String[3];
String x = "*";
for (int i= 0; i < array.length; i++)
{
array[i] = "";
array[i] = array[i] + x;
system.out.println(array[i]);
x = x + "*";
}
這將打印輸出,
*
**
***
你的數組是一個char數組,所以每個元素都包含一個char。因此,你的輸出將是:
*
*
*
爲了得到你想要的輸出,你需要一個String數組(或沒有數組在所有 - 你可以使用一個嵌套循環代替)。
此外,x = x+2;
不會做你認爲它做的事。它爲x
分配了一個新字符。如果x
的初始值爲'*'
,則它將將其更改爲數字值高於2的字符,與'*'
的數字值相比較。
替代我很想能夠在使用數組做。可能嗎? – 2015-03-19 07:00:50
@SimonKatimba更改'char array [] = new char [3];'to'String [] array = new String [3];'並將所需值分配給該數組。 – Eran 2015-03-19 07:02:33
對於您需要更改數組爲String類型, concat *
在它的每個級別。 代碼
String array[] = new String[3];
char x = '*';
array[0]=""+x;
for (int i= 0; i < array.length; i++)
{
System.out.println(array[i]);
if(i!=array.length-1)
array[i+1]='*'+array[i];
}
,你也有這麼多的編譯錯誤,在你的代碼一樣For
,Array
,system
。
還要檢查DEMO
謝謝。代碼起作用。 – 2015-03-19 07:22:47
@SimonKatimba我的榮幸 – silentprogrammer 2015-03-19 07:24:24
考慮到你了就把它可以從以下
String s="*";
StringBuffer sb =new StringBuffer();
for(int i=1;i<=4;i++)
{
System.out.println(sb.append(s));
}
輸出導出將 * **
鍀
只需提供已有答案的替代方案,也可以僅與char
一起使用。然後的技巧是使用System.out.print()
而不是System.out.println()
。舉個例子:
int n = 3; //the number of lines you want to print
char x = '*';
for(int i = 0; i < n; i++) {
for(int j = 0; j <= i; j++) {
System.out.print(x);
}
System.out.print("\n");
}
注意:這僅僅是對已經提出的解決方案
我的輸出是: 陣列[I] + X 陣列[I] + X 陣列[I] + X – 2015-03-19 07:10:11
@SimonKatimba肯定的,因爲我把數組[I] + X在'」「'誤。檢查我編輯的答案,它應該打印輸出,如我所說 – Apurva 2015-03-19 07:12:57
非常感謝你。它的工作原理 – 2015-03-19 07:22:03