练习1:写一个程序,打印1到100的值
for(int i=1;i<=100;i++){ System.out.println(i); }
练习2:写一个程序,产生25个int类型的随机数,对于每一个随机数,使用if-else语句来对其分类为大于,小于或等于紧随它而生成的的值。
分析:因为涉及两个值,需要维护两个域。
import java.util.*; public class test { public static void main(String[] args) { Random rand1 = new Random(); Random rand2 = new Random(); for(int i = 0; i < 25; i++) { int x = rand1.nextInt(); int y = rand2.nextInt(); if(x < y) System.out.println(x + " < " + y); else if(x > y) System.out.println(x + " > " + y); else System.out.println(x + " = " + y); } } }
练习3:修改练习2,把代码用while无限循环包括起来,然后运行直到键盘中断(ctrl-C)
import java.util.*; public class test { public static void main(String[] args) { Random rand1 = new Random(); Random rand2 = new Random(); while(true) { int x = rand1.nextInt(); int y = rand2.nextInt(); if(x < y) System.out.println(x + " < " + y); else if(x > y) System.out.println(x + " > " + y); else System.out.println(x + " = " + y); } } }
练习4:写一个程序,使用两个嵌套for和取余操作来探测和打印素数
import java.util.*; public class test { public static void main(String[] args) { for(int i=1;i<=100;i++){ if(i<=3){System.out.println(i+"是素数");continue;} int flag=1; for(int j=2;j<i;j++){ if(i%j==0) {System.out.println(i+"不是素数");flag=0;break;} } if(flag==1) System.out.println(i+"是素数"); } } }
练习5:用三元操作符和按位操作符来显示二进制的1和0从而代替Integer.toBinaryString
import java.util.*; public class test { static String f(int x){ String result=""; while(x!=0){ int temp=x&1; result=temp+result; x=x>>1; } return result; } public static void main(String[] args) { for(int i=1;i<=100;i++){System.out.println(i+"="+f(i));} } }