Java基础
import java.util.Scanner;
import java.util.Stack;
class Animal {
private String name;
private String bark;
private int age;
private int weight;
public Animal(String idname, String idbark, int idage, int idweight) {
// 不是说没有指针吗,这个this又是啥. 你的实例化方法第一个参数还不也是Demo* this,你写语言给我写好的啊.
this.name = idname;
this.bark = idbark;
this.age = idage;
this.weight = idweight;
}
public void showStatus() {
System.out.printf("\nname: %s,\nbark: %s,\nage: %d,\nweight: %d.", name, bark, age, weight);
}
public void sleep() {
System.out.printf("\n%s is sleeping.", name);
}
}
// 类的继承
class Penguin extends Animal {
public Penguin(String myName, String myBark, int myAge, int myWeight) {
super(myName, myBark, myAge, myWeight);
}
}
public class App {
// 递归函数.
public static int factorial(int x) {
if (x == 0 || x == 1) {
return 1;
}
else if (x < 0) {
return -1;
}
else {
return x * factorial(x - 1);
}
}
// 进制转换,试试Java的栈;
public static String Jinzhi(int num, int std) {
char[] T = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y', 'Z' };
boolean flag = true;
if (num < 0) {
num = -num;
flag = false;
}
if (num == 0) {
return "0";
}
// Java 封装的栈:
Stack<Character> st = new Stack<>();
while (num != 0) {
st.push(T[num % std]);
num /= std;
}
String result = "";
if (!flag) {
result += "-";
}
while (!st.empty()) {
result += st.pop();
}
return result;
}
public static void main(String[] args) throws Exception {
// 输入输出:
System.out.print("\nType an int: ");
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
sc.close();
System.out.printf("\n%d 的阶乘为: %d", a, factorial(a));
// 父类.
Animal cat = new Animal("cat_1", "meow", 3, 15);
cat.showStatus();
// 子类.
Penguin pgin = new Penguin("penguin_1", "gagaga", 3, 15);
pgin.showStatus();
int[] arr = new int[10];
int temp;
for (int i = 0; i < 10; i++) {
System.out.printf("\n%d! = %d", i, temp = factorial(i));
arr[i] = temp;
}
System.out.printf("\n255 的 16 进制: %s", Jinzhi(255, 16));
}
}我发现这个 Java 真的很别扭,没有左值引用,全是值传递,我就改一个引用值,我还要写一层类包装起来,没有缺省时候的默认参数,八嘎.