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);