我正在尝试创建一个简单的程序来输出用户输入的星数.我正在尝试学习如何使用多种方法来完成此任务
这是我的代码
import java.util.Scanner;
public class Alpha
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
int n;
System.out.println("Enter no. of stars");
n = input.nextInt();
}
public static void Loop ()
{
for (int counter = 1; counter <= n; counter++)
{
System.out.println("*");
}
}
}
我面临的问题是在Loop方法中,我无法使用变量n
有没有办法在另一个中使用main方法中的变量?
泰
-Pingu
解决方法:
import java.util.Scanner;
public class Alpha
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
int n;
System.out.println("Enter no. of stars");
n = input.nextInt();
Loop(n); //calls Loop function and passes parameter n
}
public static void Loop(int n) //this function now expects a number n
{
for (int counter = 1; counter <= n; counter++)
{
System.out.println("*");
}
}
}
标签:java,variables,methods
来源: https://codeday.me/bug/20190823/1695088.html