一、控制流程
块的作用:(块)是指由一对花括号括起来的若干java语句。块确定了JAVA的作用域。
public static void main(String[] args)
{
int n;
...
{
int k;
}//k is only defined up to here
}
比如下列声明就是错误的:
public static void main(String[] args)
{
int n;
...
{
int k;
int n;//ERROR-can't redefine in inner blcok
}
}
二、循环
package demo10;
import java.io.Console;
import java.util.*;
public class java1
{
public static void main(String[] args) {
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 every day?");
double payment = in.nextDouble();
System.out.println("Interest rate in %");
double interestRate = in.nextDouble();
double balance = 0;
int years = 0;
while(balance<goal)
{
balance+=payment;
double interest = balance * interestRate/100;
balance += interest;
years++;
}
System.out.println("You can retire in" + years +"years");
}
}
}
三、多重选择:SWITCH语句
Scanner in = new Scanner(System.in);
System.out.println("Select option(1,2,3,4)");
int choice = in.nextInt();
switch(choice)
{
case 1:
///
break;
case 2:
///
break;
case 3:
///
break;
default:
//bad input
break;
}
switch 语句将从与选项值相匹配的 case 标签处开始执行直到