简体   繁体   中英

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.

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

You don't need to pass Scanner to your method. 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. Instead, declare your method as

static String promptInsuredName(String insured, String input) {

and pass the result of input.nextLine() to it. This way your method will work even if the input is not generated by Scanner and CLI. In general, you need to separate the input from its parsing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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