Java基础知识

异常处理

try{} catch(Exception e){}
void work() throws Exception {} //抛出异常
throw new  Exception("输入的字符不能为空!"); 

class MyException1 extends Exception {  //自定义异常类
    String msg = null;
    public MyException1(String m) {     this.msg = m;    }
    public String  toString() {    return "抛出自定义异常:" + msg;    }
}
public class test {
   public static void main(String[] args) {
       int i = 10;
       try{
            if (i < 100) {
                throw new MyException1("输入值小于100");   //抛出异常
             }
        } catch (MyException1 ex) {
               System.out.println(ex);   //会调用ex.toString()方法
           }
    }
}

 

输入流

import java.util.Scanner;  //包含这个包
Scanner in=new Scanner(System.in); //新建流对象
int a=in.nextInt();  //输入int型
double d=in.nextDouble();  //输入double型
String s=in.nextLine(); //输入字符串

输出

System.out.println("输入有误"); //自带换行的输出
System.out.println(a);  //可以输出int等各种类型的数据
System.out.printf("%d\n",a);  //与c语言类似的格式
System.out.print(P[i].id+" "+P[i].name+" "+P[i].age+"\n"); //与cout类似
System.out.print(String.format("%4d\n",c)); //控制格式的输出

类型转换

String str="abc";
 char[ ]  c=str.toCharArray();  //String转换为char[]
char[ ] c={'a','b','c'};
 String str=new String(c);  //char[] 转换为String
String s="34";
int Age=Integer.parseInt(s); //String转换为int
double e=Double.parseDouble(es); //String转换为double
Math.abs();  //绝对值函数,很多数学中的函数都要加Math.才能调用
String ans=String.format("%.6f", T2); //控制格式直接将数转换为字符串
String[] sub=s.split(" |\n");  //以某些分隔符将一个字符串分隔

开数组

double[][] A=new double[N+1][N+1]; //二维double 型
int[] B=new int[N]; //以为int型
String[] S=new String[N]; //String 型
int C[100]; //跟C类似
多维就多加几个[]

 

posted @ 2016-08-26 20:08  wust_ouyangli  阅读(139)  评论(0编辑  收藏  举报