使用另一个方法中主要方法中的变量 [英] Use Variable Which is in main method in Another Method

查看:54
本文介绍了使用另一个方法中主要方法中的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个简单的程序来输出用户输入的星数.我正在尝试学习如何使用一种以上的方法来做到这一点 这是我的代码

I'm trying to create a simple program to output the number of stars entered by user. I'm trying to learn how to use more than one method to do this Here's my code

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方法中的另一个方法中的变量? Ty

The problem I'm facing is that in the Loop method, I am unable to use the variable n Is there a way to use a variable which is in the main method, in another one? Ty

-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("*");
    }
}
}

这篇关于使用另一个方法中主要方法中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆