Java基础小结

来源:互联网 发布:邹城农村淘宝网点查询 编辑:程序博客网 时间:2024/05/17 08:37

1.字符串的长度

String  str = new String(" abcd");

int length = str.length();

2.数组的长度

2.1对于 a[][] 
a.length代表a的行数      a[i].length代表a的列数
2.2对于a[]    
  a.length代表a的长度

3.字符串与字符数组的转化

String str = new String("abcd");

char [] a = str.toCharArray();

4.字符串数字与数字的转化

4.1 String—>int

String str = "1234";

int i = Integer.parseInt(str);  //可能会抛出异常 ,(如果报错)在 main(String[] args)后面加上throws Exception

4.2 int —>String

int i=235;

String s = String.valueOf(i);  //Of大写

5.从.in文件导入数据

import java.IO.*;

public static void main(String [] args) throws IOException{  //会抛出异常

FileReader a = new FileReader("D-small-attempt1.in");//文件与源码在同一目录下
BufferedReader read = new BufferedReader(a);
String textLine="";
String str="";
while(( textLine=read.readLine())!=null){
            str+=textLine+" ";
}
String[] numbersArray=str.split(" ");   //将str按空格分开,保存成字符数组

}

6.导处数据到.txt文件

import java.IO.*;

FileWriter fw = new FileWriter("output.txt");  
BufferedWriter bufw = new BufferedWriter(fw);  
        String line = null;  
        for(int i=1;i<n+1;i++){  
            bufw.write("Case #"+i+": "+result[i]);  
            bufw.newLine();    //下一行
            bufw.flush();     //更新
        }  
       bufw.close(); 

7.保留有限位小数

import java.text.*

DecimalFormat sim = new DecimalFormat("0.000000");//保留多少位小数点后面就有几位
double six = sim.format(source); //将source保留六位小数

比较简单的方法(对于输出结果保留有限位小数)

System.out.printf("%.3f",a);

0 0