简体   繁体   English

将变量传递给方法

[英]Passing variables into methods

I have a program that is asking for a name of an insured person.我有一个程序要求被保险人的姓名。 I am making a method called promptInsuredName and want to know the best way to pass those variables into the method.我正在创建一个名为 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


Insured and scanner input are passed into the promptInsuredName method被保险人和扫描仪输入被传递到 promptInsuredName 方法

You don't need to pass Scanner to your method.您不需要将Scanner传递给您的方法。 In general we need to make our methods as agnostic to the input as possible, yet, if you pass Scanner , then you assume that a Scanner is being used.通常,我们需要使我们的方法尽可能与输入无关,但是,如果您通过Scanner ,则您假设正在使用Scanner Instead, declare your method as相反,将您的方法声明为

static String promptInsuredName(String insured, String input) {

and pass the result of input.nextLine() to it.并将input.nextLine()的结果传递给它。 This way your method will work even if the input is not generated by Scanner and CLI.这样,即使输入不是由Scanner和 CLI 生成的,您的方法也能正常工作。 In general, you need to separate the input from its parsing.通常,您需要将输入与其解析分开。

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

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