使用java函数添加数字 [英] Add numbers with java function

查看:137
本文介绍了使用java函数添加数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

应该从用户添加数字的代码是:如果在main函数中添加了函数,那么它添加的功能不同于此处的代码显示的不同函数



Code that should add numbers from user is: if function is added in main function then it adds however not as different function as the code here shows

public class AddVariation
{
    
    public static void main(String[] args) 
    {
        AddNumbers(C,D);        
    }
    
    private static int AddNumbers(int C, int D)
    {
        Scanner Num = new Scanner(System.in);
        System.out.print("Number C :");
        while(!Num.hasNextInt()) Num.next();
        C = Num.nextInt();           
        
        System.out.print("Number D :");
        while(!Num.hasNextInt()) Num.next();
        D = Num.nextInt();   
        
        return (C+D);        
    }
} 





我的尝试:



Java代码,java类和数学函数



What I have tried:

Java code , java classes and Mathematical functions

推荐答案

您的代码不正确。您正尝试使用两个参数(C和D)调用 AddNumbers ,但您尚未定义这些变量。由于 AddNumbers 方法尝试从控制台读取值,因此没有任何意义。您需要在将要使用它们的方法中声明您的两个数字变量。最后在 main 中,您需要保存返回的值并对其执行操作,例如将它打印在控制台上。
Your code is incorrect. You are trying to call AddNumbers with two parameters (C and D), but you have not defined theses variables. And since the AddNumbers method tries to read the values from the console it makes no sense. You need to declare your two number variables inside the method that will be using them. And finally in main you need to save the returned value and do something with it, e.g. print it on the console.


现在添加另一种方式



Did it another way it adds now

public class AddVariation
{
    
    public static void main(String[] args) 
    {
           int sum =  AddNumbers();
    }
    
    private static int AddNumbers()
    {
       Scanner Num = new Scanner(System.in);        
        
       System.out.print("Number C :");
       int C = Num.nextInt();
                
       System.out.print("Number D :");
       int D = Num.nextInt();   
        
       System.out.print("Sum is :" + (C + D)); 
       
       return(C+D);
                  
    }
} 


这篇关于使用java函数添加数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆