Scanner 是JAVA标准库中提供的一个类.
import java.util.Scanner;
public class Test2 {
public static void main(String[] args) {
//先创建一个Scanner对象,把System.in作为参数传入
// 使用import语句导入这个Scanner
// 使用scanner.nextxxx()方法来读取数据
Scanner scanner= new Scanner(System.in);
int num =scanner.nextInt();
System.out.println(num);
}
}
100
100
设计一个猜数字游戏
// 猜数字游戏
// 1.先生成一个1-100的随机数
Random random=new Random();
// [0-99]+1 => [1-100]
int toGuess = random.nextInt(100)+1;
// 2.循环的提示用户输入一个数字
Scanner scanner = new Scanner(System.in);
while(true){
System.out.println("请输入一个数字:");
int num = scanner.nextInt();
if (num<toGuess) {
System.out.println("小了");
}else if (num>toGuess) {
System.out.println("大了");
}else {
System.out.println("猜对啦");
break;
}
}
请输入一个数字:
4
小了
请输入一个数字:
55
小了
请输入一个数字:
77
小了
请输入一个数字:
88
大了
请输入一个数字:
80
猜对啦
方法
方法就是函数 函数就是方法
本质是就是一段可以被重复使用的代码片段 每个方法一般都是只完成一个工作.
// 阶乘求和
int result = 0;
for(int num = 1;num<=5;num++){
result+=factor(num);
}
System.out.println(result);
}
public static int factor(int num){
int result =1 ;
for(int i = 1;i<=num;i++){
result*=i;
}
return result;
}
}
153
方法调用的过程 一旦遇到方法调用的代码 就会跳转到方法内部执行(同时会把实参的值赋给形参)顺序执行方法内部代码 方法内部遇到return或者方法执行完毕的时候,代码就会回到调用位置继续执行。
方法内部的代码一定是调用,如果没有调用,方法代码就不会被执行到
方法调用👇
Scanner scanner = new Scanner(System.in);
System.out.println("请输入两个数字:");
int a = scanner.nextInt();
int b = scanner.nextInt();
int result = min(a,b);
System.out.println(result);
}
public static int min(int x,int y){
if(x<y){
return x;
}
else{
return y;
}
}
打印九九乘法表
public static void printMultiplicationTable() {
// 乘法口诀是一行一行打印的。
for(int row = 1;row<=9;row++){
printline(row);
}
}
public static void printline(int row) {
// 只打印一行
// 第row行里面有row列
for (int col = 1;col<=row;col++){
System.out.print(col+"x"+row+"="+col*row+" ");
}
System.out.println();
}
}
1x1=1
1x2=2 2x2=4
1x3=3 2x3=6 3x3=9
1x4=4 2x4=8 3x4=12 4x4=16
1x5=5 2x5=10 3x5=15 4x5=20 5x5=25
1x6=6 2x6=12 3x6=18 4x6=24 5x6=30 6x6=36
1x7=7 2x7=14 3x7=21 4x7=28 5x7=35 6x7=42 7x7=49
1x8=8 2x8=16 3x8=24 4x8=32 5x8=40 6x8=48 7x8=56 8x8=64
1x9=9 2x9=18 3x9=27 4x9=36 5x9=45 6x9=54 7x9=63 8x9=72 9x9=81
Process finished with exit code 0
注:按行去打印 列数×行数
求两个数的最大公约数 代码👇
// 求两个整数的最大公约数
int result = calcGCD(100,120);
System.out.println(result);
}
public static int calcGCD(int a, int b) {
int min =min(a,b);
for (int i = min;i>=1;i--){
if(a%i == 0 && b%i == 0 ){
return i;
}
}
return 1;
}
20