第一题:
- 编写 Java 程序,请按照以下要求,在Example05类中进行测试。,实现银行存取款业务。
(1)定义一个银行账户类BankAccount实现银行账户的概念。
(2)账户的属性包括账号和存款余额,需要在BankAccount类中定义两个变量:“账号” (account_number) 和“存款余额”(leftmoney)。
(3)对账户的操作包括存款、取款、查询余额,所以再定义四个方法:“存款”(savemoney)、“取款”(getmoney) 、“查询余额”(getleftmoney)以及构造方法(BankAccount)。
(4)最后,编写测试类,在main()方法中创建一个BankAccount类的对象ba,假设ba的账号为:123456,初始的存款余额为600元。首先向该账户存入2000元,再取出1000元
代码如下:
private String account_number;
private double leftmoney;
// 构造方法(BankAccount)。
public BankAccount(String account_number, double leftmoney) {
this.account_number = account_number;
this.leftmoney = leftmoney;
}
// 存款(savemoney)方法。
public void savemoney(double money) {
leftmoney += money;
System.out.println("存入" + money + "元成功!当前余额为" + getleftmoney() + "元。");
}
// 取款(getmoney)方法。
public void getmoney(double money) {
if (leftmoney >= money) {
leftmoney -= money;
System.out.println("取出" + money + "元成功!当前余额为" + getleftmoney() + "元。");
} else {
System.out.println("余额不足!");
}
}
// 查询余额(getleftmoney)方法。
public double getleftmoney() {
return leftmoney;
}
}
// 测试类。
class mian {
public static void main(String[] args) {
// 在main()方法中创建一个BankAccount类的对象ba,假设ba的账号为:123456,初始的存款余额为600元。
BankAccount ba = new BankAccount("123456", 600);
// 首先向该账户存入2000元。
ba.savemoney(2000);
// 再取出1000元。
ba.getmoney(1000);
}
}
运行结果:
存入2000.0元成功!当前余额为2600.0元。
取出1000.0元成功!当前余额为1600.0元。
第二题:
请用while循环输出1,3,5,7,9,...100
代码如下:
public class t1 {
public static void main(String[] args) {
int i = 1;
while (i <= 100) {
System.out.println(i);
i += 2;
}
}
}
第三题:
请用for循环输出100,95,90,85,...0
代码如下:
public class t2 {
public static void main(String[] args) {
int i = 100;
while (i >= 0) {
System.out.println(i);
i -= 5;
}
}
}
第四题:
用你喜欢的循环结构输出1,2/3,3/5,4/7,5/9…的前20项的数字
提示:最简单的是在循环中使用两个计数器,一个每次加1,一个每次加2。还有一种难些,就是分析分母是由分子的一个通配公式组成的。
public class t3 {
public static void main(String[] args) {
int i = 1;
int j = 1;
while (j <= 20) {
System.out.println(i + "/" + j);
i += 1;
j += 2;
}
}
}
第五题:
中国目前的GDP为14.5万亿美元,年均GDP增长7%,请问到2050年,我国GDP为多少?
代码如下:
public class t4 {
public static void main(String[] args) {
double currentGDP = 14.5 * Math.pow(1.07, 20);
int years = 20;
double growthRate = 1.07 / 100;
double futureGDP = currentGDP * Math.pow((1 + growthRate), years);
System.out.println("到2050年,我国GDP为:" + futureGDP + "万亿美元");
}
}