簡體   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