发表于: 2017-08-12 23:49:41

2 949



今天完成的任务


学习了循环


1.if循环



if (i==1)
System.out.println(1);
System.out.println("这行不受影响");//这种方式if语句只影响下面一行代码
if (i==2)
System.out.println(2);
if (i==3)
System.out.println(3);
if (i==4)
System.out.println(4);//这样代码每次都会判断一次
//if else if
       if(i==1){
System.out.println(1);
}else if(i==2){
System.out.println(2);
}else if(i==3){
System.out.println(3);
}else{
System.out.println("都不是");
}

if关键字循环有以下几种写法..()内为布尔值

1)if()...;else...;不带{},这种方式if只影响下一行的代码

2.if(){};else{};,{}里面随便写

3.if(){}:else if();,可以限定复数的限定条件



2.switch语句

switch (day) {//switch可以使用byte,short,int,char,String,enum,但是enum是枚举类型
   case 1:
System.out.println("星期一");
break;//以break结尾
   case 2:
System.out.println("星期二");
break;
case 3:
System.out.println("星期三");
break;
case 4:
System.out.println("星期四");
break;
case 5:

和if语句差不多,以break;结尾。条件可以是基础数据类型。String和enum。



3.while语句


while(i<5) {
System.out.print(i);//先判断再进行执行
   i++; }
do{ System.out.println(j);
j++; }while(j<5);{
System.out.println(j+"+"+i); }//do—while为循环主体,必定会先执行一次再进行判断

while有两种形式

1.while(){};{}内为循环主体,会先判断是否符合条件,再执行

2.do{}while();{},do{}内为循环主体,并且,会先执行一次再去判断是为符合条件



4.for语句

for(int i=0;i<10;i++){
j=j*2;
//  System.out.println(j);
}

这个是一般最常用的循环语句



5.break

for (int j = 0; j < 10; j++) {
System.out.println(i+":"+j);
if(0==j%2)
break; }

break会中断当前的循环


6.通过标签返回语句

//通过标签返回,这个似乎是java残留的goto语句
outloop: //outloop这个标示是可以自定义的
//System.out.println("outloop");//////////////为什么在标签之下,循环之上添加语句会报错,而且为啥只能在循环之上添加标签
for (int a = 0; a < 10; a++) {
for (int b = 0; b < 10; b++) {
System.out.println(a+":"+b);
if(0==a%2)
break outloop; //返回到标签位置?
   }

我自己试了一下,返回的标签只能加在循环语句之上,并且两者之间不能有其他语句,不太清楚原理


7.通过循环,查找20以内的数相除的商最近似0.618的一组数值

package ThirdDay.ThirdPractice;

public class PracticeTheGoldenSection {
public static void main(String[] args){
int numerator_j=0;//储存分子
       int  denominator_i=0;//储存分母
       float goldline=0.618f;
float Goldline=0f;//储存相除的结果
       float k;
for(int i=1;i<=20;i++){
for(int j=1;j<i;j++){
if (i%2==0&j%2==0)
continue;
k=(float)j/i;
// System.out.print(k);
               if(Math.abs(k-goldline)<Math.abs(Goldline-goldline)){//如果循环中两个数的商与0.618的差的绝对值小于存储的商与0.618的差的绝对值
                   System.out.print("ssssssssssssss");
Goldline=k;//重新赋值
                   denominator_i=i;
numerator_j=j;
}
}
}
System.out.print(denominator_i+" "+ numerator_j+" "+ Goldline);
}
}

思路为遍历循环,返回每一组数值的商,在此利用逻辑运算符排除不符合条件的数,然后通过比较得出结论



明天的任务

接着往下看


遇到的问题

1.

//通过标签返回,这个似乎是java残留的goto语句
outloop: //outloop这个标示是可以自定义的
//System.out.println("outloop");//////////////为什么在标签之下,循环之上添加语句会报错,而且为啥只能在循环之上添加标签
for (int a = 0; a < 10; a++) {
for (int b = 0; b < 10; b++) {
System.out.println(a+":"+b);
if(0==a%2)
break outloop; //返回到标签位置?
   }

为什么返回标签,只能返回到循环之前,并且标签与循环之间不能有其它语句

2.

for(int i=1;i<=20;i++){
for(int j=1;j<i;j++){
if (i%2==0&j%2==0)
continue;
k=(float)j/i;

在这个循环里,曾发生无法给变量k赋值,后强制转型为浮点型float后解决


收获

打基础..我也不太清楚收获具体有什么,不过今天自己写出了一个循环语句的代码,也算有所收获吧


返回列表 返回列表
评论

    分享到