Java 模块化编程
知识点:创建自定义方法,方法调用,多重分支 switch,数组
方法就是一段可重复调用的代码段,例如:有某段长度约 100 行的代码,要在多个地方使用
此段代码,如果在各个地方都重复编写此部分代码的话,则肯定会比较麻烦,而且此部分代
码如果修改的话也比较困难,所以此时可以将此部分代码定义成一个方法,以供程序反复调
用。
例题1.
write a menu system using switch():
On opening the menu should look something like this:
WTU Bank – Main Menu
1.
Create New Account
2.
Deposit
3.
Withdraw
4.
Balance
5.
Exit
Please input your choose(1-5):____
all other selections except 5 should print out “You have selected <your selection>”
and return to the main menu. Selection 5 should exit.
(使用switch()编写一个菜单系统:在打开菜单时,应该是这样的: WTU银行-主菜单1。创建新的帐户2。存款3。退出4。平衡点5。退出请输入您的选择(1-5):____除5之外的所有其他选择应该打印出“您已经选择了<您的选择>”并返回到主菜单。选择5应退出。)
package week2;
import java.util.Scanner;
public class Menu {
public static void main(String[] args) {
//TODO Auto-generated method stub
//显示菜单
//用户输入
//将上述功能封装为一个方法,需要时间调用,实现代码的复用
int choice=menu();
while(choice!=5) {
switch(choice) {
case 1: createAccount() ;break;
case 2: deposit() ;break;
case 3: withDraw() ;break;
case 4: balance();break;
default:System.out.println("选择无效!");
}
//继续显示菜单
choice=menu();
}
System.out.println("程序结束");
}
/**
* 显示菜单 用户输入
*/
public static int menu() {
int choice = 0;
System.out.println("===WTU Bank – Main Menu===");
System.out.println("1. Create New Account");
System.out.println("2. Deposit");
System.out.println("3. Withdraw");
System.out.println("4. Balance");
System.out.println("5. Exit");
System.out.println("Please input your choose(1-5):____");
Scanner sca=new Scanner (System.in);
choice=sca.nextInt();
return choice;
}
public static void createAccount() {
System.out.println("创建新用户");
}
public static void deposit() {
System.out.println("存钱");
}
public static void withDraw() {
System.out.println("取钱");
}
public static void balance() {
System.out.println("查询");
}
}
数组是一组相关数据的集合,一个数组实际上就是一连串的变量。
例题2.
Create a Java program to input 5 student results as a numeric grade (0-100). If a
grade entered is less than 0 or greater than 100 ask for re-entry of that particular
grade. Your program is to calculate and display the class average grade and also
display the highest and lowest grades when the appropriate
menu option is chosen. (创建一个Java程序,将5个学生成绩作为数字分数(0-100)。如果输入的分数小于0或大于100,要求重新进入该特定等级。你的程序是计算和显示班级平均成绩,并在选择适当的菜单选项时显示最高和最低成绩。)