参数和常量

本文介绍了Java编程的基础概念,包括方法参数的使用,参数仅作为原始值拷贝,不会影响外部变量。探讨了方法的重载,即同名方法的不同签名。讲解了如何编写具有返回值的方法,并提供了实际案例,涉及计算物体下落轨迹的代码,利用Scanner对象获取用户输入,结合数学公式进行计算。同时,文章还提到了String对象的不可变性和substring方法的使用规则。
摘要由CSDN通过智能技术生成

一:java方法中参数的限制

package Pricitise;

public class lianxi {
	public static void main(String[] args){
//		int x = 7;
//		doubleNumber(x);
//		System.out.println("x="+x);
//		System.out.println();
//		
		int number = 800;
		doubleNumber(number);
		System.out.println("number="+number);
		System.out.println("y="+y);
	}	
		
		public static void doubleNumber(int number){
		System.out.println("初始值为"+number);;
		number = number*2;
		System.out.println("最终值为"+number);
		int y = number;
		
	}
}

方法中对参数的局部操作并不会改变方法以外实际变量的值。参数的一个重要特性就是:它只是原始变量值的一份拷贝。好的一面是:我们知道变量不会被调用的方法所修改,因为方法的参数只是原始值的拷贝。不好的一面是,我们只能通过参数将一些值传送到方法中去,但是不能通过参数将方法中的某些值提取出来。

二:重载
多个方法共用一个名字,但是每个同名的不同方法必须有不同的方法签名。即方法名以及参数的个数和类型。

三:编写具有返回值的方法

public static void main(String[] args){
				int answer = sum(100);
				System.out.println(answer);
		}
public static int sum(int n){
		return (n+1)*n/2;
    }

return语句应该作为方法的最后一条语句。

四:String对象
String对象值不可变。
在这里插入图片描述substring的第二个参数要落在字所提取的字串之外。
在这里插入图片描述

五:Scanner对象
在这里插入图片描述
Scanner console = new Scanner(System.in);
int n = console.nextInt();

六:实际案列

package Pricitise;
import java.util.Scanner;
import org.omg.Messaging.SyncScopeHelper;
public class gravity {
	public static final double ACCELERATION = -9.81;//类常量
		public static void main(String[] args){
			Scanner console = new Scanner(System.in);
			System.out.println("velocity");
			double velocity = console.nextDouble();
			System.out.println("angle(degree)");
			double angle = Math.toRadians(console.nextDouble());
			System.out.println("number of steps to display");
			int steps = console.nextInt();
			System.out.println();
			
			double xVelocity = velocity*Math.cos(angle);
			double yVelocity = velocity*Math.sin(angle);
			double totaltime = -2.0*yVelocity/ACCELERATION;
			double timeIncrement = totaltime/steps;
			double xIncrement = xVelocity*timeIncrement;
					
			double x=0.0;
			double y=0.0;
			double t=0.0;	
			System.out.println("stept\tx\ty\ttime");
			System.out.println("0\t0.0\t0.0\t0.0");
		
			for(int i = 1;i<= steps;i++){
				t += timeIncrement;
				x += xIncrement;
				y = yVelocity*t+0.5*ACCELERATION*t*t;
				System.out.println(i+"\t"+round2(x)+"\t"+round2(y)+"\t"+round2(t));
		   }	
			
     }
		public static double round2(double n){
			return Math.round(n*100)/100.0;
		}
	
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值