JavaCore_控制流程_0509

JavaCore控制流程

知识来源

JavaCore (卷一)

控制流程

学习顺序 :块作用域、条件语句、循环语句、switch语句

说明

Java控制流程类似C++,很少例外。无goto、break可以带标签,用于跳出内层循环(c中用goto)、有一种变形的for循环,类似C#中的 foreach 循环。

块作用域 block

就是{}括起来的区域。块与块可以嵌套,但不能在嵌套块中redifinition变量。

条件语句

加入块就是条件为真时可以执行多条语句。if语法同c系列,不再赘述。

循环语句

写一个Demo名为Retirement.java

while
import java.util.*;

public class Retirement{
	public static void main(String[] args) {
		// read inputs
		Scanner in = new Scanner(System.in);

		System.out.println("How Much Money Do You Need To Retire");
		double goal = in.nextDouble();

		System.out.println("How Much Money Will You Contribute Each Year");
		double payment = in.nextDouble();

		System.out.println("Interest rate in %: ");
		double interestRate = in.nextDouble();

		double balance = 0;
		int years = 0;

		// update account while goal isn't reached
		while (balance < goal) {
			// add this year's payment and interest
			balance += payment;
			double interest = balance * interestRate / 100;
			balance += interest;
			years++;
		}

		System.out.println("You Can Retire In " + years + " Years.");
	}
}
do while
		do{
			balance += payment;
			balance += interestRate * balance / 100;
			
			years++;
			System.out.printf("After year %d, your balance is %,.2f%n", years, balance); // 不会
			System.out.printf("Exit?(Y/N)");
			input = in.next(); //.next()方法
		}
		while (input.equals("N"));
确定循环 for
int i;
for (int i = 1; i < 10; i++)
  • 如果在 for 中声明了变量,它是不允许在外部使用的,比如示例中的i。要在外部使用的话要像在代码段中一样在外部声明;

  • for是while的简化形式;可把样例改成如下形式:

    int i = 1;
    while (i < 10)
    {
    	/* code */  
    }
    
switch语句
  • 一般不用,为了避免在某个case中没有break;
  • case标签可以是char、byte、short或int的常量表达式、枚举类型、字符串字面量;
String input = ...;
switch (input)
{
  case "yes" : // ok since JAVA SE 7 字符串字面量
    ...
    break;
}
  • 用枚举时枚举名可以不写。
Size sz = ....;
switch (sz)
{
  case SMALL : // no need to use size Size.SMALL
    ...
    break;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值