[英]return incompatible types (java)
原文:好的,所以我必須做一個簡單的數字金字塔,但是要注意的是它必須使用兩種方法。 我的問題是,返回值總是給我“不兼容的類型”,我不知道為什么。 好的,所以我必須制作一個簡單的數字金字塔,但要注意的是它必須使用兩種方法。 我的問題是,返回值總是給我“不兼容的類型”,我不知道為什么。
public static void main(String[] args)
{
System.out.println(NumPyramid(1,1));
}
public static int NumPyramid(int i, int j)
{
for (;i <= 7; i++)
{
for (; j <= i; j++)
{
{
return System.out.print(j + " ");
}
}
}
編輯:好的,所以現在我的新代碼存在不是金字塔的問題
public static void main(String[] args)
{
NumPyramid(1,1);
}
public static void NumPyramid(int i, int j)
{
for (;i <= 7; i++)
{
for (; j <= i; j++)
{
System.out.print(j + " ");
}
System.out.println();
}
}
打印出來
1 2 3 4 5 6 7
刪除Println會得到1 2 3 4 5 6 7
輸出應為1 12 123
等,
System.out.print
是一個void
方法; 也就是說,它什么也不返回。
您不能從void
方法返回某些內容。
只需從該行中刪除return
關鍵字,即可將方法的簽名從int
更改為void
。
然后,在您的main方法中更改調用以從中刪除System.out.println
。
好吧,正如@makoto巧妙地指出的那樣, System.out.print
是一個void
方法,它什么也不返回:
public static void main(String[] args) {
System.out.println(NumPyramid(1,1));
}
也應該更改。 所以你應該做:
public static void NumPyramid(int i, int j) {
for (;i <= 7; i++) {
for (; j <= i; j++) {
System.out.print(j + " ");
}
}
}
無效方法,以及:
public static void main(String[] args) {
NumPyramid(1,1);
}
沒有打印。
編輯
當您收到一個新問題時,您將不能編輯您的問題,也不要刪除該問題帖子中的內容以使其成為新問題……而是接受最佳答案,然后發表新帖子。 在這里,我們不僅要回答您的問題 ,而且還在建立知識庫。 如果您有新問題,請發布新帖子!
也就是說,對於您的新問題,您要關閉的算法是:
public static void NumPyramid(int max) {
for (int i=1; i<=max; ++i) {
for (int j=1; j<=i; ++j)
System.out.println(j + " ");
System.out.println();
}
}
max
來指定行數和金字塔“底”的寬度; i
迭代以獲取max
回車輸出; j
代表i
編號進行迭代 max = 3
,我們不輸出0 1 2
,而是1 2 3
應該輸出,最大= 3
1
1 2
1 2 3
再次。 請恢復您原來的問題。
您要打印嗎?
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
您需要一個參數,它是方法:
public static void NumPyramid(int number)
{
for (int i = 1; i <= number; ++i)
{
for (int x = 1; x <= i; ++x)
{
System.out.print(x + " ");
}
System.out.println();
}
}
我認為這是不言而喻的
我猜您不再問不兼容的返回類型了嗎? 好吧,我想我可以回答你現在的問題。
如果要將代碼放在金字塔中,則不能執行以下操作:
for (;i <= 7; i++)
{
for (; j <= i; j++)
{
System.out.print(j + " ");
}
System.out.println();
}
該代碼正在執行的操作是先打印j的值,然后打印一個空格,然后打印新行。 一種解決方案是創建一個String,用於在for循環的每次迭代之后存儲數字。
for (;i <= 7; i++)
{
for (; j <= i; j++)
{
//System.out.print(j + " ");
//The string would take the place of this line
}
//Since println always prints on a new line, you
//could just print the string in this System.out
System.out.println();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.