卓音第三次博客
数据类型
之前写的忘保存了,两次了=-=
println(5+5+"is"); #10is
println("is"+5+5) #is55
api scanner类
String next(); 遇到空格或tab就不录入
String nextLine(); 回车为录入结束的标记
如果所有数据都是字符串,用next Line()
若还有其他类型,用next()
String类
String s="abc"
等于String s=new String(abc);
遍历字符串
1:
String s="aaa"; char[]str=s.toCharArray(); for(int i;i<str.length();i++) //这是调用字符串的方法 { println(str[i]); }
2:
String s="aaa"; char[]str=s.toCharArray(); for(int i;i<str.length;i++) //这是数组的属性 { char c = str.charAt(i); println(c); }
字符串的截取
String s="abc";
String str=s.substring(0,1);
String str1=s.substring(1);
println(str) //a
println(str2) //bc
StringBuilder
提高字符串操作效率
正则表达式
通常用来登录用户名,密码
String s="[abc]"; System.out.println("b".matches(s)); //true
[abc]只能是abc其中之一
[a]只能是a
[^abc]除了abc以外任何
[a-zA-Z]a到z,A到Z
[a-z&&[【^bc]]&&为交集,a-z除了b和c
预定义字符类
String s="."; .为任意字符,一个.对应一个字符
String s=".+";不限个数
\d一个数字
异常
处理异常
package text; import java.util.Scanner; public class text { public static void main(String[] args) { while (true) { try { System.out.println(inMoney()); break; } catch (Exception e) { System.out.println("数字"); } } } public static int inMoney() { Scanner sc = new Scanner(System.in); int price; while (true) { System.out.println("输入价格"); price = sc.nextInt(); if (price <= 0) { System.out.println("错误"); } else { System.out.println("yes"); return price; } } } }
自定义异常类
public clsaa AgeillRuntimeException extends RuntimeException{ public class AgeillRuntimeException(String message){ super(message); } }
public class ExceptionText2{ public static void main(String[] args){ try{ saveAge(160); System.out.printf("yes") }catch(Exception e){ e.printStackTrace(); System.out.println("bug!") } } public static void saveAge(int age){ if(age>0&&age<150){ System.out.println("ok"); }else{ throw new AgeillRuntimeException("illegal") } } }