while循环
语法
while(条件){
...
}
打印1~100所有数字
package cn.edu360.javase24.day02;
/**
* 打印1~100
* @author cho
*
*/
public class WhileDemo {
public static void main(String[] args) {
int i=1;
while(i<=100){
System.out.println(i);
i++;
}
}
}
打印1~100所有奇数
package cn.edu360.javase24.day02;
/**
* 打印1~100所有的奇数
*
* @author cho
*
*/
public class WhileDemo2 {
public static void main(String[] args) {
int i = 1;
while (i <= 100) {
if ((i & 1) == 1)
System.out.println(i);
i++;
}
}
}
for循环
语法
for(...){
...
}
猜数游戏
package cn.edu360.javase24.day02;
import java.util.Scanner;
/**
* 猜数游戏
*
* @author cho
*
*/
public class GuessNum {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// 内置一个数字
int ans = 34;
for (int i = 1; i <= 3; i++) {// 循环3次
System.out.printf("第%d次机会: \n", i);
int gn = Integer.parseInt(sc.nextLine().trim());
if (gn > ans) {
System.out.println("数字大了");
} else if (gn < ans) {
System.out.println("数字小了");
} else {
System.out.println("恭喜你!猜对了!");
return;
}
}
System.out.println("很遗憾,机会用完,游戏结束.");
}
}
案例: 求平均成绩
需求
需求:
用户可以输入5门课程的分数
我们的程序来计算5门课程的总分、平均分
实现步骤
package array;
import java.util.Scanner;
/**
* 数组
* 计算多门成绩的总分,平均分
* @author cho
*
*/
public class GetScore {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// 定义一个长度为5的数组
double[] score = new double[5];
for(int i=0;i
System.out.println("请输入成绩: ");
score[i]=Integer.parseInt(sc.nextLine().trim());
}
// 计算总成绩
double sum=0;
for(int i=0;i<5;i++)
sum += score[i];
System.out.println("总成绩: "+sum);
System.out.printf("平均成绩: %.2f\n",sum/5);
}
}
涉及的知识点
如何定义数组?
double[] q = new double[N];
int[] q = new int[N];
数组中有个常用属性 length
for(int i=0;i
...
}
数组遍历
需求
将一个数组中的数据 从前到后打印
将一个数组中的数据 从后到前打印
实现步骤
package array;
/**
* 数组遍历
*
* @author cho
*
*/
public class ArrayTraverse {
public static void main(String[] args) {
int[] q = new int[10];
for (int i = 0; i < q.length; i++)
q[i] = i;
// 顺序打印
for (int i = 0; i < q.length; i++)
System.out.printf("%d ", q[i]);
System.out.println();
// 逆序打印
for (int i = q.length - 1; i >= 0; i--)
System.out.printf("%d ", q[i]);
}
}
涉及的知识点
逆序遍历
for(int i=q.length-1;i>=0;i--){
...
}
数组排序
需求
假如有一个班级的所有学生的总成绩保存在一个数组中[50,60,30,80,70]
需要写一个程序将这个数组中的数据按分数的大小排序[30,50,60,70,80]
实现步骤
package array;
public class BubbleSort {
static int[] q = { 50, 60, 30, 80, 70 };
static void bubble_sort(int l, int r) {
if (l >= r)
return;
int n = q.length;
for (int i = 0; i < n - 1; i++) {
boolean f = false;
for (int j = 0; j + 1 < n; j++) {
if (q[j] > q[j + 1]) {
int t = q[j];
q[j] = q[j + 1];
q[j + 1] = t;
f = true;
}
}
if (!f)
break;
}
}
public static void main(String[] args) {
bubble_sort(0, q.length);
for (int i = 0; i < q.length; i++)
System.out.printf("%d ", q[i]);
}
}
涉及的知识点
冒泡排序
这是一个基础排序...