第二章 JAVA 控制结构

JAVA的7种结构

(且为 无Goto 语句编程)

基本结构:顺序结构

三种选择结构: if       if/else    switch

三种循环结构: while    do/while    for

 ————————————————————————————————————————————————————

//为提高可读性,建议每一层缩进的长度固定为3个空格

//println 自动换行 

//  int grade =10; System.out.println( grade );  JAVA中输出不需要和C一样%d

java中条件运算符                      条件?  a:b 

 int grade=10;
 System.out.println( grade>20 ? "good": "hehe");

————————————————————————————————————————————————————

public static void main( String args[ ] ) throws IOException                  //main 方法必须以此开头

/*使用方法System.out.print时,有时输出的字符串会放到一个缓冲区,不显示到屏幕上

此时用 System.out.flush 方法讲强制显示缓冲区的字符*/

而使用 System.out.println 不需要使用flush,将自动强制输出显示在屏幕上

throws IOException  向编译器指出忽略可能输入的异常

注意:使用输入一个字符并且按上一个字符,换行符也会自动输入,所以可以用System.in.skip ( 1 );    //跳过一个输入的字符


求10个学生的平均成绩

	public static void main(String args[]) throws IOException
   {    //a 3 b2 c1 d0 
		int q;  int total = 0;
		int grade; int average;
		for (q=0;q<10;q++)
		{
		  grade = System.in.read(); 
		  
		  if(grade == 'a')
			  total += 3;
		  if(grade == 'b')
			  total += 2;
		  if(grade == 'c')
			  total += 1;
		  
		}
		System.in.skip(1);
		average= total/10;
		System.out.println(average);
		
   }   

______________________________________________________________________________________________________________________________

自顶向下,逐步求精 (标志控制循环)

//标志值得选择:应该选择一个不合法的数据组

 //a 3 b2 c1 d0 
		int q;  int total = 0; int count =0;
		int grade; int average;
		for (q=0;q<10;q++)
		{
		  grade = System.in.read();
		 // System.in.skip(1);
		  if( grade == 'z' )
			  break;
		  
		  if(grade == 'a')
			  total =total+ 3;
		  if(grade == 'b')
			  total =total+ 2;
		  if(grade == 'c')
			  total =total+ 1;
		  
		  System.in.skip(1);
		  count++;  
 		  
		  
		}
		count=count/2;
		System.out.println(count);
		average= total/count;
		System.out.println(average);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值