分支结构
与C语言一样
package stl;
import java.util.Scanner;
public class basic {
public static void main(String[] args) {
System.out.println("Please input your heartbeat:");
Scanner sc = new Scanner(System.in);
int heartBeat = sc.nextInt();
if (heartBeat < 60 || heartBeat > 100) {
System.out.println("Your heartbeat is " + heartBeat + " per min,you maybe need to check more advanced!");
} else {
System.out.println("Your heartbeat is " + heartBeat + " per min,you are healthy!");
}
System.out.println("Check Finished");
int score = sc.nextInt();
if (score >= 0 && score < 60) {
System.out.println("Your score is C");
} else if (score >= 60 && score < 80) {
System.out.println("Your score is B");
} else if (score >= 80 && score < 100) {
System.out.println("Your score is A");
}`在这里插入代码片`
}
}
循环结构
for循环
int n = sc.nextInt();
for (int i = 1; i <= n; i++) {
System.out.println("I ❤ U China");
}
当然for也可以这么写
for(;i<j;){
i+=2;
}
来用java求水仙花数
public class basic {
public static void main(String[] args) {
for (int i = 100; i <= 999; i++) {
int bit_001 = i % 10;
int bit_010 = i / 10 % 10;
int bit_100 = i / 100;
if (bit_001 * bit_001 * bit_001 + bit_010 * bit_010 * bit_010 + bit_100 * bit_100 * bit_100 == i) {
System.out.print(i+"\t");
}
}
}
}
while循环
与C语言一样
int i=0;
while (i<3){
sout("Hello");
i++;
}
do while循环
与C语言一样
int i=1;
do{
sout("Helloworld");
i++;
}while(i<3);
break,continue,goto
与C语言一样
随机数
import java.util.Random;
Random random = new Random();
int n = random.nextInt(10) + 1;//[1,10)
写一个猜数字的案例
package stl;
import java.util.Scanner;
import java.util.Random;
public class basic {
public static void main(String[] args) {
System.out.println("来玩猜数游戏吧");
Scanner scanner = new Scanner(System.in);
Random random = new Random();
System.out.println("请输入猜测数字整数区间");
System.out.println("左区间");
int lt = scanner.nextInt();
System.out.println("右区间");
int rt = scanner.nextInt();
int LuckyNumber = random.nextInt(rt - lt) + lt;
System.out.println("区间设立:" + lt + "到" + rt);
System.out.println("请输入猜测数字");
int cnt = 0;
while (true) {
int guess = scanner.nextInt();
cnt++;
if (guess < LuckyNumber) {
System.out.println("太小了!");
} else if (guess > LuckyNumber) {
System.out.println("太大了!");
}
if (guess == LuckyNumber) {
System.out.println("恭喜你猜对啦!您总共猜了" + cnt + "次");
break;
}
}
}
}