JAVA基础知识+基础代码

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)); //控制格式的输出
Math.abs();  //绝对值函数,很多数学中的函数都要加Math.才能调用
String ans=String.format("%.6f", T2); //控制格式直接将数转换为字符串
String[] sub=s.split(" |\n");  //以某些分隔符将一个字符串分隔
类型转换
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
开数组
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类似
多维就多加几个[]
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值