如何将参数值从一种方法传递到同一类中的另一种方法

如何解决如何将参数值从一种方法传递到同一类中的另一种方法

我正在为具有存款,提款和余额查询功能的ATM模拟器编写此代码。该代码需要使用方法而不是switch语句编写。 我的存款方法可行,但是我的提款和 balanceInquiry 方法都存在问题。我希望所有方法都可以访问 checkAc_bal ,以便执行计算。我是Java的新手,我正在尝试将方法行为归于我。非常感谢。

...

import java.util.Scanner;
public class Main
{
    public static void showMenu()
    {
        Scanner sc = new Scanner(System.in) ;
        String input = null ;
        do
        {
            input = showOptions(sc) ;
            if(input != null)
            {
                switch(input.trim())
                {
                    case "1" :    deposit(sc) ;
                        break ;
                    case "2" :    withdraw(sc);
                        break ;
                    case "3" :    balanceInquiry() ;
                        break ;enter code here
                    case "4" :    System.exit(0);
                    default  :  System.out.println("Wrong option entered. Exiting application") ;
                        System.exit(0);
                }
            }
        }while(true) ;
    }

    public static String showOptions(Scanner sc)
    {

        System.out.println("********************Welcome to ATM Machine******************** ");
        System.out.println("Enter Option");
        System.out.println("1. Deposit");
        System.out.println("2. Withdrawal");
        System.out.println("3. Balance Inquiry");
        System.out.println("4. Exit\n");
        String input = sc.nextLine() ;
        return input ;
    }
    
     public static void deposit (Scanner sc) {
        int checkAc_bal = 0;
        System.out.print("Enter amount to be deposited:");
        int deposit;
        Scanner s = new Scanner(System.in);
        deposit = s.nextInt();
        //int checkAc_bal = 0;

        checkAc_bal = checkAc_bal + deposit;

        System.out.println("Your Money has been successfully deposited");
        System.out.println("Balance: " +checkAc_bal);
    }

    public static void withdraw (Scanner sc){
        System.out.print("Enter money to be withdrawn:");
        int withdraw;
        Scanner s = new Scanner(System.in);
        withdraw = s.nextInt();
        if(withdraw<=checkAc_bal)
        {
            checkAc_bal = checkAc_bal - withdraw;
            System.out.println("Please collect your money");
        }
        else
        {
            System.out.println("Insufficient Balance");
        }
        System.out.println("");
    }

    public static void balanceInquiry () {
        System.out.println("Balance: " + checkAc_bal);
    }
    
    public static void main(String[] args) {
        showMenu();
    }
}

解决方法

如果希望int可被其他方法访问,则需要在整个类的范围内而不是在方法内部声明它。尝试在Main类中声明checkAc_bal。

,

将其定义为类成员:

import java.util.Scanner;
public class Main
{
    static int checkAc_bal = 0;   //<------------------------add this

    public static void showMenu()
    {
        Scanner sc = new Scanner(System.in) ;
        String input = null ;
        do
        {
            input = showOptions(sc) ;
            if(input != null)
            {
                switch(input.trim())
                {
                    case "1" :    deposit(sc) ;
                        break ;
                    case "2" :    withdraw(sc);
                        break ;
                    case "3" :    balanceInquiry() ;
                        break ;enter code here
                    case "4" :    System.exit(0);
                    default  :  System.out.println("Wrong option entered. Exiting application") ;
                        System.exit(0);
                }
            }
        }while(true) ;
    }

    public static String showOptions(Scanner sc)
    {

        System.out.println("********************Welcome to ATM Machine******************** ");
        System.out.println("Enter Option");
        System.out.println("1. Deposit");
        System.out.println("2. Withdrawal");
        System.out.println("3. Balance Inquiry");
        System.out.println("4. Exit\n");
        String input = sc.nextLine() ;
        return input ;
    }
    
     public static void deposit (Scanner sc) {
//        int checkAc_bal = 0;  <---------------- remove this 
        System.out.print("Enter amount to be deposited:");
        int deposit;
        Scanner s = new Scanner(System.in);
        deposit = s.nextInt();
        //int checkAc_bal = 0;

        checkAc_bal = checkAc_bal + deposit;

        System.out.println("Your Money has been successfully deposited");
        System.out.println("Balance: " +checkAc_bal);
    }

    public static void withdraw (Scanner sc){
        System.out.print("Enter money to be withdrawn:");
        int withdraw;
        Scanner s = new Scanner(System.in);
        withdraw = s.nextInt();
        if(withdraw<=checkAc_bal)
        {
            checkAc_bal = checkAc_bal - withdraw;
            System.out.println("Please collect your money");
        }
        else
        {
            System.out.println("Insufficient Balance");
        }
        System.out.println("");
    }

    public static void balanceInquiry () {
        System.out.println("Balance: " + checkAc_bal);
    }
    
    public static void main(String[] args) {
        showMenu();
    }
}
,

您有三个查询,以下是答案:

  1. 将变量全局声明为可从所有方法访问。
  2. 不使用切换大小写(在这种情况下,您需要使用if-else)
  3. 如何将参数传递给相同类中的方法? 我看到您已经在代码中做到了这一点。您通过参数调用了其他方法,并且也收到了它们。

或者根据您的实际需求很好地提出问题。

这是完整的代码:

import java.util.Scanner;

public class Main{

    static int checkAc_bal = 0;  // <---- declare on class scope

    public static void showMenu()    {
        Scanner sc = new Scanner(System.in) ;
        String input = null ;
        do {
            input = showOptions(sc) ;
            if(input != null) {
                // removed the switch-case and if-else used
                if(input.trim().equals("1"))      {deposit();} 
                else if(input.trim().equals("2")) {withdraw();}
                else if(input.trim().equals("3")) {balanceInquiry();}
                else if(input.trim().equals("4")) {System.exit(0);}
                else {
                    System.out.println("Wrong option entered. Exiting application") ;
                    System.exit(0);
                }
            }
        }while(true) ;
    }

    public static String showOptions(Scanner sc){

        System.out.println("********************Welcome to ATM Machine******************** ");
        System.out.println("Enter Option");
        System.out.println("1. Deposit");
        System.out.println("2. Withdrawal");
        System.out.println("3. Balance Inquiry");
        System.out.println("4. Exit\n");
        String input = sc.nextLine() ;
        return input ;
    }
    
     public static void deposit () {
        
        System.out.print("Enter amount to be deposited:");
        int deposit;
        Scanner s = new Scanner(System.in);
        deposit = s.nextInt();
        checkAc_bal = checkAc_bal + deposit;

        System.out.println("Your Money has been successfully deposited");
        System.out.println("Balance: " +checkAc_bal);
    }

    public static void withdraw (){
        System.out.print("Enter money to be withdrawn:");
        int withdraw;
        Scanner s = new Scanner(System.in);
        withdraw = s.nextInt();
        if(withdraw<=checkAc_bal) {
            checkAc_bal = checkAc_bal - withdraw;
            System.out.println("Please collect your money");
        } else {
            System.out.println("Insufficient Balance");
        }
        System.out.println("");
    }

    public static void balanceInquiry () {
        System.out.println("Balance: " + checkAc_bal);
    }
    
    public static void main(String[] args) {
        showMenu();
    }
}

输出:

********************Welcome to ATM Machine******************** 
Enter Option
1. Deposit
2. Withdrawal
3. Balance Inquiry
4. Exit

1
Input : 1
Enter amount to be deposited:100
Your Money has been successfully deposited
Balance: 100
********************Welcome to ATM Machine******************** 
Enter Option
1. Deposit
2. Withdrawal
3. Balance Inquiry
4. Exit

1
Input : 1
Enter amount to be deposited:200
Your Money has been successfully deposited
Balance: 300
********************Welcome to ATM Machine******************** 
Enter Option
1. Deposit
2. Withdrawal
3. Balance Inquiry
4. Exit

1
Input : 1
Enter amount to be deposited:200
Your Money has been successfully deposited
Balance: 500
********************Welcome to ATM Machine******************** 
Enter Option
1. Deposit
2. Withdrawal
3. Balance Inquiry
4. Exit

3
Input : 3
Balance: 500
********************Welcome to ATM Machine******************** 
Enter Option
1. Deposit
2. Withdrawal
3. Balance Inquiry
4. Exit

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-