格式:
修饰符 返回值类型 方法名(参数列表){
//代码省略...
return 结果;
}
//用于对比查看,帮助理解
public static int suShu(){
return 0;
}
public static void main(String[] args) {
sum(1,100);//方法调用
}
public static void sum(int x,int y){
int s = 0;
for (int i = x; i < y; i++) {
if (i%2==0){
s+=i;
}
}
System.out.println(x + "到" + y +"的偶数和为:"+s);
}
注意:static
可以方便在没有创建对象的情况下来进行调用(方法/变量),初学者建议加上static
,做大型项目时static的使用需要慎重,下面额外延伸一下没有static时怎样调用方法(不过这个应该算是面向对象的内容)。
public class demo13 {
public static void main(String[] args) {
demo13 demo13 = new demo13();
demo13.sum(1,100);//方法调用
}
public void sum(int x,int y){
int s = 0;
for (int i = x; i < y; i++) {
if (i%2==0){
s+=i;
}
}
System.out.println(x + "到" + y +"的偶数和为:"+s);
}
}
通过对比可以发现,不加入static
需要new
一个对象出来,但是被static
修饰的方法在main
方法启动的时候就被加载进内存,这也就是为什么大型项目使用static
需要慎重的原因。
public static void main(String[] args) {
int n = suShu();
System.out.println("素数个数为:"+n);
}
public static int suShu(){
int sum = 0;//统计素数个数
for (int i=101;i<=200;i++){
boolean flag = true;//默认为真
for (int j=2;j<i;j++){
if (i%j==0){
flag = false;//如果为假则说明当前i不为素数
}
}
if (flag){
sum++;
}
}
return sum;
}
public static void main(String[] args) {
int m = power(3,3);//方法调用
System.out.println(m);
}
public static int power(int x,int n){
int m = 1;
for (int i = 0; i < n; i++) {
m*=x;
}
return m;
}
数组存储的数据类型[] 数组名字 = new 数组存储的数据类型[长度];
数据类型[] 数组名 = new 数据类型[]{元素1,元素2,元素3...};
数据类型[] 数组名 = {元素1,元素2,元素3...};
int[] arr = new int[3];
int[] arr = new int[]{1,2,3,4,5};
int[] arr = {1,2,3,4,5};
public static void main(String[] args) {
int[] arr = { 1, 2, 3, 4, 5 };
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
length()
:数组的长度
注意:
数组的索引从0开始
public static void main(String[] args) {
int[] arr = {15,89,13,25,62,68,5};
int num = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > num){
num = arr[i];
}
}
System.out.println("数组中的最大值为:" + num);
}
public static void main(String[] args) {
int[] arr = {15,89,13,25,62,68,5};
for (int i = 0; i < arr.length-1; i++) {
for (int j=0;j<arr.length-i-1;j++){
if (arr[j]<arr[j+1]){
int tem = arr[j];
arr[j] = arr[j+1];
arr[j+1] = tem;
}
}
}
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
冒泡排序是一个经典算法,他不是最优算法,但是这个必须要掌握。下面从百度上搜了一张图,便于理解
数组越界异常
public static void main(String[] args) {
int[] arr = {1,2,3};
System.out.println(arr[3]);
}
上述代码中,数组的索引有0,1,2
并没有3,所以会出现ArrayIndexOutOfBoundsException
异常。在开发中,数组的越界异常是不能出现的,一 旦出现了,就必须要修改我们编写的代码。
空指针异常
public static void main(String[] args) {
int[] arr = {1,2,3};
arr = null;
System.out.println(arr[0]);
}
解析:
arr = null
这行代码,意味着变量arr将不会在保存数组的内存地址,也就不允许再操作数组了,因此运行的时候 会抛出 NullPointerException
空指针异常。
本文地址:https://blog.csdn.net/qq_45740561/article/details/107282868
如对本文有疑问, 点击进行留言回复!!
集合框架——Map、泛型以及Collection算法常用方法
Elasticsearch 升级 7.x 版本后,我感觉掉坑里了
Mybatis的插件运行原理以及如何编写一个Mybatis的插件
网友评论