使用主方法中的方法 java

To use method from the main method java

这个问题非常适合我的问题,这就是为什么我要创建一个新问题。该程序中的第二种方法应该使数字 1 2 3 4 5 6 7 8 9 10 成为一行。我遇到的唯一问题是我不知道如何在主要方法中打印出来。

public class Uppgift1_6a 
{
    public static void main(String[] args) 
    {
        for(int k = 0; k < 10; k++)
        {
            int tal = Numberline(k);
            System.out.print(tal);
        }
    }

    public static int Numberline(int tal1) 
    {
        int tal = 1;
        for(int i = 1; i < 11; i++)
        {
            tal = tal1 + i;
        }
        return tal;
    }
}

现在它打印出从 11 到 19 的所有数字。如果我更改它,它只会打印出 10 或 11。

仔细看代码:

public static int Numberline(int tal1)
{
    int tal = 1;
    for (int i = 1; i < 11; i++)
    {
        tal = tal1 + i;
    }
    return tal;
}

for 循环实际上什么都不做——您只返回最终结果。最后的结果总是正好等于tal1 + 10;同样,for 循环在这一点上所做的没有区别。 (我鼓励您使用调试器逐句调试代码,让自己相信这一事实)。

如果您希望它在您通过 for 循环时打印出这些值,您需要执行如下操作:

for (int i = 1; i < 11; i++)
{
    // You may need to modify this line too, depending on what values you want printed
    tal = tal1 + i;
    // Print the value here
    System.out.print(tal);
}

因为您编写它的方式只会打印出 tal(您返回的那个)的 最终 值。