从零开始学Java-Day05
测试break和continue
package cn.tedu.review;
import java.util.Scanner;
//本类用于测试break和continue
public class TestBreakAndContinue {
public static void main(String[] args) {
/*
* 加了continue可以提高效率,
* break 和 continue后面不可以直接加代码
*/
Scanner scan = new Scanner(System.in);
for (int i = 0; i < 10; i++) {
System.out.println("请输入数字:");
int num = scan.nextInt();
if (num == 88) {
System.out.println("猜对了");
break;
}else {
System.out.println("猜错了!还剩下" + (10-i) + "次机会");
}
}
scan.close();
}
}
while 和 do - while
package cn.tedu.review;
import java.util.Random;
import java.util.Scanner;
//本类用于while 和 dowhile循环
public class TestWhile_dowhile {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = creatNum();
//System.out.println(n);
while (true) {//死循环,需要设置程序的出口
System.out.println("输入一个数");
int num = scan.nextInt();
if (num == n) {
System.out.println("猜对了!");
break;
}else if (num > n) {
System.out.println("大了");
}else {
System.out.println("小了");
}
}
scan.close();
}
public static int creatNum() {
//100以内的随机整数
int num = new Random().nextInt(10);
return num;
}
}
数组
package cn.tedu.array;
//用于数组的遍历
public class TestArrayExec {
public static void main(String[] args) {
int[] months = {31,28,31,30,31,30,31,31,30,31,30,31};
for (int i = 0; i < months.length; i++) {
System.out.println(i + 1 + "月: " + months[i] + "天");
}
}
}
int[] a = new int[10];
变量a存放的是new int[10]的地址!!!
package cn.tedu.array;
import java.util.Arrays;
//此类用于练习数组的创建
public class TestCreatArrary {
public static void main(String[] args) {
int[] a = new int[5];//动态创建
//静态创建
int[] b = new int[]{1,2,3,4,5};
int[] c = {1,2,3,4,5};
char[] ch1 = {'a','b','c','d'};
char[] ch2 = new char[] {'1','s','3','h'};
//动态创建
/**
* 通过数组下标操作数组中的元素
* 从0开始
* 最大长度 = 数组长度 - 1
*/
char[] ch3 = new char[5];
ch3[0] = 'a';
ch3[1] = 'b';
ch3[2] = 'c';
ch3[3] = 'd';
ch3[4] = 'e';
//打印数组
/**
* char类型底层做了处理,可以直接打印数组中的具体元素内容
* 除了char意外的类型的数组,想要打印数组元素
* 需要使用数组的工具类Arrays.toString(数组名)方法
* 注意:Arrays使用是的工具包:Java.util.Arrays
*/
System.out.println(Arrays.toString(a));
System.out.println(Arrays.toString(b));
System.out.println(Arrays.toString(c));
System.out.println(Arrays.toString(ch1));
System.out.println(Arrays.toString(ch2));
System.out.println(Arrays.toString(ch3));
System.out.println((a));
System.out.println((b));
System.out.println((c));
System.out.println((ch1));
System.out.println((ch2));
System.out.println((ch3));
String[] s = {"emt", "486", "lm"};
System.out.println(s);
//查看数组的长度-数组元素的个数(legenth)
System.out.println(a.length);
System.out.println(b.length);
System.out.println(c.length);
System.out.println(ch1.length);
System.out.println("emt".toCharArray());
}
}
posted on 2021-06-07 19:41 无声specialweek 阅读(48) 评论(0) 编辑 收藏 举报