繁体   English   中英

将变量传递给方法

[英]Passing variables into methods

我有一个程序要求被保险人的姓名。 我正在创建一个名为 promptInsuredName 的方法,并且想知道将这些变量传递到该方法中的最佳方法。

import java.util.Calendar;

public class BurtonLavato002PA2 {

    String message = "", coverage = "";
    double payout = 0.0, deductible = 0.0;
    boolean repeat;

    public static void main(String[] args){
        Scanner input = new Scanner(System.in);
        char cont = ' ', correct = ' ', another = ' ';
        String insured = " ";
        double homeInsVal = ' ', richter = ' ';
        Calendar dateTime = Calendar.getInstance();


        System.out.println("MUTUALLY ACCIDENTAL, INC.");
        System.out.printf("%nDo you want an analysis of earthquake coverage for your property? Enter 'Y' or 'N':  ");
        cont = input.next().charAt(0);
        input.nextLine();

        while(cont == 'Y' || cont == 'y'){
            promptInsuredName(insured, input);

            

            }// END OF WHILE


        }// END OF MAIN

    static String promptInsuredName(String insured, Scanner input) {
        System.out.printf("%nMUTUALLY ACCIDENTAL, INC.");    //Header for the prompt
        System.out.printf("%nEarthquake Coverage Analyzer");

        System.out.printf("%n%nPlease enter your name:  ");
        insured = input.nextLine(); // Take input under the Scanner stdin to read insured name.
        return insured;
    } // END OF promptInsuredName


    }// END OF CLASS


被保险人和扫描仪输入被传递到 promptInsuredName 方法

您不需要将Scanner传递给您的方法。 通常,我们需要使我们的方法尽可能与输入无关,但是,如果您通过Scanner ,则您假设正在使用Scanner 相反,将您的方法声明为

static String promptInsuredName(String insured, String input) {

并将input.nextLine()的结果传递给它。 这样,即使输入不是由Scanner和 CLI 生成的,您的方法也能正常工作。 通常,您需要将输入与其解析分开。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM