示例代码:
- class Demo{ //类名Demo
- public static void main(String args[])throws Exception{ //抛出异常
- char ch;
- System.out.println("Press a key followed by Enter:"); //打印信息
- ch=(char)System.in.read(); //从键盘输入system.in.read();
- System.out.println("Your key is:"+ch); //打印输入的字符
- }
- ------------------------------------------------------------------------------------------------------------
- if else if 以及嵌套
- int i;
- for(i=0;i<6;i++){
- if(i==1){
- System.out.println("i is one");
- }else if(i==2){
- System.out.println("i is two");
- }else if(i==3){
- System.out.println("i is three");
- }else if(i==4){
- System.out.println("i is four");
- }
- else{
- System.out.println("i is not between one to four");
- }
- }
- ------------------------------------------------------------------------------------------------------------
- for循环
- int fact=1;
- int i;
- int sum=0;
- for(i=1;i<=5;i++){
- sum+=i; //1-5的和
- fact*=i; //1-5的阶乘
- System.out.println("sum="+sum);
- System.out.println("fact="+fact);
- System.out.println();
- }
- System.out.println(i);
- }
- -----------------------------------------------------------------------------------------------------------
- While循环
- char ch='a';
- while(ch<='z'){
- System.out.println(ch);
- ch++;
- }
- ----------------------------------------------------------------------------------------------------------
- do while循环
- char ch;
- int count=0;
- System.out.println("请输入字符串,以句号结束");
- do{
- ch=(char)System.in.read();
- if(ch==' ') count++;
- }while(ch!='.');
- System.out.println("count"+count);
- ---------------------------------------------------------------------------------------------------------
- switch语句
- int i;
- for(i=0;i<10;i++){
- switch(i){
- case 0:
- System.out.println("i is zero");
- break; //break终止循环
- //continue结束本次循环继续下次循环
- case 1:
- System.out.println("i is one");
- break;
- case 2:
- System.out.println("i is two");
- break;
- case 3:
- System.out.println("i is three");
- break;
- case 4:
- System.out.println("i is four");
- break;
- default:{
- System.out.println("i is five or more");
- }
- }
- }
- }