Java笔记

发布 : 2021-03-07 分类 : 笔记 浏览 :

初学Java,有些东西需要记录一下。

Part 1

Java的方法只能传值,不能传引用,但是可以用对象来解决这个问题。

例如swap函数:

方案1:构造一个新类MyInteger

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class SwapTwoNumbers {
static class MyInteger {
private int a;
public MyInteger(int a) {
this.a = a;
}
public int getValue() {
return a;
}
public void changeValue(int a) {
this.a = a;
}
}
public static void swap(MyInteger a, MyInteger b) {
int t = a.getValue();
a.changeValue(b.getValue());
b.changeValue(t);
}
public static void main(String[] args) {
MyInteger a = new MyInteger(4);
MyInteger b = new MyInteger(10);
System.out.println("a is "+a.getValue()+" and b is "+b.getValue());
swap(a, b);
System.out.println("a is "+a.getValue()+" and b is "+b.getValue());
}
}

方案2:利用main所在的类本身

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class t1 {
int a, b;
public t1(int a, int b) {
this.a = a;
this.b = b;
}
public void swap() {
int t = a;
a = b;
b = t;
}
public static void main(String[] args) {
t1 x = new t1(3,4);
System.out.println("a is "+x.a+" and b is "+x.b);
x.swap();
System.out.println("a is "+x.a+" and b is "+x.b);
}
}

方案3:利用数组

1
2
3
4
5
public static void swap(int[] data, int a, int b) {
int t = data[a];
data[a] = data[b];
data[b] = t;
}

Part2

求gcd。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import java.util.Random;

public class t1 {
public static int gcd(int a, int b) {
//if(a <= 0 || b <= 0) return 0;
if(a%b==0) return b;
return gcd(b, a%b);
}
public static void main(String[] args) {
Random r = new Random();
int a = r.nextInt(), b = r.nextInt();
a=Math.abs(a); b=Math.abs(b);
System.out.println(a+" "+b);
if(a<b) System.out.println(gcd(b,a));
else System.out.println(gcd(a,b));
}
}

求素数。

本文作者 : preccrep
原文链接 : https://preccrep.github.io/2021/03/07/Java%E7%AC%94%E8%AE%B0/
版权声明 : 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明出处!
留下足迹

博客已萌萌哒运行(●'◡'●)ノ♥
Theme - BMW | Made With 💗 | Powered by GodBMW