public class ForDemo1 {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
System.out.println("HelloWorld");
}
System.out.println("--------------------------------------------");
for (int i = 1; i <=10 ; i++) {
System.out.println("HelloWorld1");
}
System.out.println("--------------------------------------------");
for (int i = 1; i <=10 ; i+=2) {
System.out.println("HelloWorld2");
}
}
}
public class ForDemo2 {
public static void main(String[] args) {
// 目标:打印输出1-100的数据,求1-100的和
for (int i = 1; i < 101; i++) {
System.out.println(i);
}
int sum = 0;
System.out.println("---------------------------------------");
for (int i = 1; i <= 100 ; i++) {
sum += i;
}
System.out.println(sum);
System.out.println("----------------------------------------");
/**
* 计算1-100之间的奇数和
*/
int sum1 = 0;
for (int i = 0; i < 100; i++) {
if (i % 2 == 1){
sum1 += i;
}
}
System.out.println(sum1);
}
}
2.while循环
// while循环
public class WhileDemo3 {
public static void main(String[] args) {
int i = 0;
while (i < 5){
System.out.println("HelloWorld");
i++;
}
}
}
3.do-while循环
public class DoWhileDemo5 {
public static void main(String[] args) {
int i = 0;
do {
System.out.println("HelloWorld");
}while (i < 0);
// while循环中的变量可以在while外部使用
System.out.println(i);
// 而for中定义的变量只能在for循环中使用,不能在外部使用
for (int j = 0;j < 4;j++){
System.out.println(j);
}
// System.out.println(j); 报错
}
}
4.死循环
public class EndLessLoopDemo6 {
public static void main(String[] args) {
// 死循环的三种写法
/*for (; ;) {
System.out.println("HelloWorld");
}*/
/* while (true){
System.out.println("HelloWorld1");
}*/
/* do {
System.out.println("HelloWorld");
}while (true);*/
}
}
5.嵌套循环
public class LoopNestedDemo7 {
public static void main(String[] args) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 5; j++) {
System.out.println("抽死你");
}
System.out.println("----------------------------------");
}
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
System.out.print("*");
}
System.out.println(); // 换行
}
}
}
6.跳转关键字
public class BreakAndContinueDemo8 {
public static void main(String[] args) {
// 目标:掌握break和continue的执行
// 1.break:跳出并结束当前所在循环
for (int i = 1; i <= 5; i++) {
System.out.println("。。。");
if (i == 3) {
break;
}
}
for (int i = 0; i < 5; i++) {
System.out.println("。。。");
if (i == 2) {
break;
}
}
for (int i = 0; i < 5; i++) {
if (i == 3) {
break;
}
System.out.println("。。。");
}
// 2.continue:提出本次循环,执行下一次循环
// 第一天干活,第二天干活,第三天休息,第四天干活
for (int i = 1; i <= 4; i++) {
if (i == 3){
System.out.println("第"+i+"天休息");
continue;
}else {
System.out.println("第"+i+"天干活");
}
}
}
}
795.区间子数组个数 class Solution {public int numSubarrayBoundedMax(int[] nums, int left, int right) {return lessEqualsThan(nums,right) - lessEqualsThan(nums,left - 1);}private int lessEqualsThan(int[] nums,int k){int len nums.length;int res 0,left 0,ri…
上链接:P3405 [USACO16DEC] Cities and States S - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)https://www.luogu.com.cn/problem/P3405
上题干: 题目描述 Farmer John 有若干头奶牛。为了训练奶牛们的智力,Farmer John 在谷仓的墙上放了一…