Scanner+Random+switch的使用

  • Scanner类
  • Random的使用
  • switch的注意事项

Scanner的使用

Scanner的常见方法:

  • nextInt() nextDouble()
  • next() nextLine()的区别

next()不能输入空格字符串

``nextLine()`可以输入空格字符串和换行,并且他不能和上面的一起使用,否则会接受换行符。有两种方法输入带空格的字符串。见下面

import java.util.Scanner;
public class Scanner_Demo{
	public static void main(String[] args){
		//创建对象
		Scanner sc = new Scanner(System.in);
		//输入整数
		System.out.println("请输入一个整数");
		int zhengshu = sc.nextInt();
		System.out.println(zhengshu);
		//输入小数
		System.out.println("请输入一个小数");
		double xiaoshu = sc.nextDouble();
		System.out.println(xiaoshu);
		//输入字符串 使用next()方法不能接受空格或者换行,
		//他们以这两个字符为结束标志,后面的就不再接受。
		System.out.println("请输入字符串");
		String zifuchuan = sc.next();
		System.out.println(zifuchuan);
		//方法一和方法二。2选1.。
		//方法一,创建另一个对象输入带空格的字符串运行时
		System.out.println("请输入字符串");
		Scanner sc1 = new Scanner(System.in);
		String line = sc1.nextLine();
		System.out.println(line);
		
		//方法二输入带空格的字符串
		sc.nextLine();//用于接收上一个的换行
		System.out.println("请输入字符串");
		
		String line = sc.nextLine();
		System.out.println(line);
		
		
		
	}
}

Random的使用

直接上

import java.util.Random;
public class Random_Demo{
	public static void main(String[] args){
		Random r = new Random();
		//生成[10,99]的随机整数
		int zhengshu = r.nextInt(90)+10;
		System.out.println(zhengshu);
		
		//生成随机小数
		double xiaoshu = r.nextDouble();
		System.out.println(xiaoshu);
		
		//使用nextDouble()生成[0,99]的随机整数;
		System.out.println("[0,99]的随机整数"+(int)(r.nextDouble()*100));
	}
}

switch语句

  • case穿透的使用
  • switch语句中,表达式的数据类型,可以是byte,short,int,char,enum(枚举),JDK7后可以接收字符串
    案例:使用case穿透实现输入一个数字,返回季节。
import java.util.Scanner;
public class Switch_Test{
	public static void main(String[] args){//月份的判断
		//输入数字
		Scanner sc = new Scanner(System.in);
		System.out.println("请输入一个数字(1-12):");
		int num = sc.nextInt();
		
		switch(num){
			case 12:				
			case 1:				
			case 2:
				System.out.println("冬季");
				break;
			case 3:				
			case 4:				
			case 5:
				System.out.println("春季");
				break;
			case 6:				
			case 7:				
			case 8:
				System.out.println("夏季");
				break;
			case 9:				
			case 10:				
			case 11:
				System.out.println("秋季");
				break;
			default :
				System.out.println("异常输入");
				break;
		}
	}
}

break的跳级使用

使用标记可以直接跳到对应的那一层嵌套里;

//标记break跳级
		a:
		while(true){
			Scanner sc = new Scanner(System.in);
			System.out.println("请输入一个数字(1-7):");
			int num = sc.nextInt();
		
			switch(num){
				case 1:
					System.out.println("星期一");
					break;
				case 8:
					System.out.println("结束");
					break a;
				default :
					System.out.println("输入有误:");
			}
		}

循环编写的小技巧

当不清楚怎么写的时候可以先编写循环体的部分,然后看哪部分是重复执行的再利用循环,有时候需要考虑breakcontinue的使用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值