方法的重载
public class Demo02 {
public static void main(String[] args) {
int max = max(10,10);
System.out.println(max);
}
//方法的重载:方法可以重名,但是要参数类型不同
public static double max(double num1,double num2){
double result = 0;
if(num1 == num2){
System.out.println("num1==num2");
return 0;
}
if(num1 > num2){
result = num1;
}else{
result = num2;
}
return result;
}
//比大小
public static int max(int num1,int num2){
int result = 0;
if(num1 == num2){
System.out.println("num1==num2");
return 0;//终止方法
}
if(num1 > num2){
result = num1;
}else{
result = num2;
}
return result;
}
}
可变参数的使用
public class Demo04 {
public static void main(String[] args) {
Demo04 demo04 = new Demo04();
demo04.test(1,2,3,4,5);
}
//这样比比较麻烦,可以用可变参数
public void method(){}
public void method(int i){}
public void method(int i,int i2){}
public void method(int i,int i2,int i3){}
//可变参数
public void test(int... i){
System.out.println(i[0]);
System.out.println(i[1]);
}
}
输出几个数的最大值
public class maxDemo {
//输出几个数中的最大值
public static void main(String[] args) {
printMax(1,2,5,41,35.5);
printMax(new double[]{1,2,5,64,84});//此处不能写为new double[1,2,3,4,5],会报错
}
public static void printMax(double...x){
if(x.length == 0){
System.out.println("没有输入数据");
return ;
}
double result =x[0];
for(int i = 1;i<x.length;i++){//将大的值赋值给result用来返回
if(x[i]>result){
result = x[i];
}
}
System.out.println("最大值为:" + result);
}
}
递归计算阶乘
- 尽量避免使用递归
public class Demo06 {
//计算阶乘
public static void main(String[] args) {
System.out.println(f(5));
}
public static int f(int n){
if(n == 1){
return 1;
}else{
return n*f(n-1);
}
}
}
一个有问题的计算程序
- scanner.close()后,运行到scanner.nextDouble处时出现异常NoSuchElementException
- 解决办法是删除scanner.close()语句,或者不循环
import java.util.Scanner;
public class calculatorTest {
public static void main(String[] args) {
while(true) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入第一个数");
double a1 = scanner.nextDouble();
System.out.println("请输入第二个数");
double a2 = scanner.nextDouble();
System.out.println("请输入运算符");
String str = scanner.next();//此处用scanner.nextLine()会直接赋值为空并进入switch
switch (str) {
case "+":
System.out.println(add(a1, a2));
break;
case "-":
System.out.println(subtraction(a1, a2));
break;
case "*":
System.out.println(multiplication(a1, a2));
break;
case "/":
System.out.println(division(a1, a2));
break;
default:
System.out.println("符号输入错误,请重新输入");
}
scanner.close();
}
}
public static double add(double x,double y){//定义加法
return x+y;
}
public static double subtraction(double x,double y){//定义减法
return x-y;
}
public static double multiplication(double x,double y){//定义乘法
return x*y;
}
public static double division(double x,double y){//定义除法
return x/y;
}
}
标签:int,double,小练,System,使用,println,方法,public,out
From: https://www.cnblogs.com/0720hzq/p/17331688.html