1、输入输出
import java.util.Scanner;//先导入类
public class Hello
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in); // 创建Scanner对象
String name = scanner.nextLine(); // 读取一行输入并获取字符串
int age = scanner.nextInt(); // 读取一行输入并获取整数
double height=scanner.nextDouble();//读取一行输入并获取带小数的值
System.out.printf("Hi,%s,you are %i,your height is %d",name,age,height);
//printf格式化,print输出后不换行,println输出后换行
}
}
2、字符串(String)和数组( [] )是引用类型
两个引用指向两个不同地址,若判断指向的内容是否相等,用equal()
s1.equal(s2);
3、浮点数计算得到的结果常常不精确,可以采用加(double)的方式
如计算为0.456,赋值结果为0,因此需要类型转换!
double percent=(double)(7-5/7);
4、可以用switch语句给某个变量赋值
int opt;
switch (fruit) {
case "apple":
opt = 1;
break;
case "pear":
case "mango":
opt = 2;
break;
default:
opt = 0;
break;
}
从Java 12开始,switch
语句升级为更简洁的表达式语法,使用类似模式匹配(Pattern Matching)
的方法,保证只有一种路径会被执行,并且不需要break
语句:
String fruit = "apple";
int opt = switch (fruit) {
case "apple" -> 1;
case "pear", "mango" -> 2;
default -> 0;
}; // 注意赋值语句要以;结束
由于switch表达式是作为Java 12的预览特性(Preview Language Features)实现的,编译的时候,我们还需要给编译器加上参数:
javac --source 12 --enable-preview Main.java
5、剪刀石头布例子
import java.util.Scanner;
/**
* switch实现石头/剪子/布并判断胜负
*/
public class Hello {
public static void main(String[] args)
{
System.out.println("please choice:");
System.out.println(" 1: Rock");
System.out.println(" 2: Scissors");
System.out.println(" 3: Paper");
// 用户输入:
Scanner scan =new Scanner(System.in);
int choice = scan.nextInt();
// 计算机随机数 1, 2, 3:
int random = 1 + (int) (Math.random() * 3);
switch (choice)
{
// TODO:
case 1:
switch(random)
{
case 1:
System.out.print("平局");
break;
case 2:
System.out.printf("你:%s,机器:%d,你赢了",choice,random);
break;
case 3:
System.out.printf("你:%s,机器:%d,你输了",choice,random);
break;
default :
System.out.print("结束");
}
break;
case 2:
switch(random)
{
case 2:
System.out.print("平局");
break;
case 3:
System.out.printf("你:%s,机器:%d,你赢了",choice,random);
break;
case 1:
System.out.printf("你:%s,机器:%d,你输了",choice,random);
break;
default :
System.out.print("结束");
}
break;
case 3:
switch(random)
{
case 3:
System.out.print("平局");
break;
case 1:
System.out.printf("你:%s,机器:%d,你赢了",choice,random);
break;
case 2:
System.out.printf("你:%s,机器:%d,你输了",choice,random);
break;
default :
System.out.print("结束");
}
break;
default :
System.out.print("请输入正确数字");
}
}
}
6、计算圆周率π
圆周率公式:
public class PI {
public static void main(String[] args)
{
double pi = 0;
for (int i = 0; i < 10000000; i++)
{
pi = 4*Math.pow(-1,i)/(2*i+1) + pi;
}
System.out.println(pi);
}
}
要注意i
的作用范围,只在循环内作用,不要在循环外使用。