当前位置:编程学习 > JAVA >>

以下是一段C++代码,请问如何才能把它改写成(调用函数的)Java代码?

#include<iostream> using namespace std; double div(double x,double y)//定义一个求商的函数 { if(y==0) { cout<<"除数为零,不合题意!\n"; exit(0); } else { return x/y; } } int main() { double x,y;//定义两个数 cout<<"请输入第一个数:"; cin>>x; cout<<"请输入第二个数:"; cin>>y; cout<<"则这两个数的商是:"<<div(x,y)<<endl; return 0; }
追问:请您给出相应的代码吧?
答案:import java.util.Scanner;


public class cDiv {
    private static double div(double x,double y) throws ArithmeticException
    {
        if (y==0) throw new ArithmeticException();
        else return x/y;
    }
    public static void main(String args[])
    {
        double a,b;
        Scanner sc=new Scanner(System.in);
        System.out.print("输入第一个数:");
        a=sc.nextDouble();
        System.out.print("输入第二个数:");
        b=sc.nextDouble();
        try
        {
        System.out.printf("则这两个数的商是: %f\n", div(a,b));
        }catch(ArithmeticException ex)
        {
            System.out.println("除数为零,不合题意!");
        }
    }
}
其他:这个很简单的。可以用Scanner类输入有很多方法,你可以自己查API文档。不会的话再问我。 

上一个:诚求《java web开发实战1200例》的源代码 卢瀚编的 谢谢~~ 536472495@qq.com
下一个:"C:\Java\jre6\bin\javaw.exe" -jar "%1" 这是什么意思怎么弄?

CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,