时间:2022-06-09 09:21:10 | 栏目:JAVA代码 | 点击:次
顺序结构比较简单,按照代码书写的顺序一行一行执行
这里补充一道笔试题:Java中不能做switch参数的数据类型有哪些?
switch语句执行流程:
1. 先计算表达式的值
2. 和case依次比较,一旦有响应的匹配就执行该项下的语句,直到遇到break时结束
3. 当表达式的值没有与所列项匹配时,执行default
switch 不能表达复杂的条件
// 例如: 如果 num 的值在 10 到 20 之间, 就打印 hehe
// 这样的代码使用 if 很容易表达, 但是使用 switch 就无法表示.
if (num > 10 && num < 20) {
System.out.println("hehe");
}
基本语法
System.out.println(msg); // 输出一个字符串, 带换行 System.out.print(msg); // 输出一个字符串, 不带换行 System.out.printf(format, msg); // 格式化输出
代码示例
System.out.println("hello world");
int x = 10;
System.out.printf("x = %d\n", x)
格式化字符串
| 转换符 | 类型 | 举例 | |
| d | 十进制整数 | ("%d", 100) | 100 |
| x | 十六进制整数 | ("%x", 100) | 64 |
| o | 八进制整数 | ("%o", 100) | 144 |
| f | 定点浮点数 | ("%f", 100f) | 100.000000 |
| e | 指数浮点数 | ("%e", 100f) | 1.000000e+02 |
| g | 通用浮点数 | ("%g", 100f) | 100.000 |
| a | 十六进制浮点数 | ("%a", 100) | 0x1.9p6 |
| s | 字符串 | ("%s", 100) | 100 |
| c | 字符 | ("%c", ‘1’) | 1 |
| b | 布尔值 | ("%b", 100) | true |
| h | 散列码 | ("%h", 100) | 64 |
| % | 百分号 | ("%.2f%%", 2/7f) | 0.29% |
char i = (char) System.in.read();
System.out.println("your char is:"+i);

当遇到这样的情况,只需要按一下 alt+回车即可

Scanner scanner = new Scanner(System.in); //输入整型数 int n = scanner.nextInt(); System.out.println(n); //输入浮点数 float a = scanner.nextFloat(); System.out.println(a); //输入字符串 String str= scanner.nextLine(); System.out.println(str);
一些解释:

当我们运行代码,发现了一些问题



在读取字符串时


//循环输入
Scanner scanner = new Scanner(System.in);
while(scanner.hasNextInt()){
int n=scanner.nextInt();
System.out.println(n);


注:如果想要看源代码

就可以看到了

import java.util.Random;
import java.util.Scanner;
public class TestDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
//生成随机数
//Random random = new Random();
Random random = new Random(1234);//括号内放一个数字,每次生产随机数都是根据这个数生成的
int randNum = random.nextInt(100);//在括号内输入100表示随机数的范围是[0,100)
int randNum2 = random.nextInt(100)+1;//表示[1,100]或[1,101)
while(true)
{
System.out.println("请输入你要猜的数字: ");
int num= scanner.nextInt();
if(num<randNum){
System.out.println("猜小了!");
}else if(num==randNum){
System.out.println("猜对了!");
break;
}else{
System.out.println("猜大了!");
}
}
}
}
分析:
生成随机数


运行程序

成功!