一些java基本程序图解2
生活随笔
收集整理的這篇文章主要介紹了
一些java基本程序图解2
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
1 水仙花數(shù)
"水仙花數(shù)"是指一個(gè)三位數(shù),其各位數(shù)字立方和等于該數(shù)本身。
例如,153 是一個(gè)"水仙花數(shù)",因?yàn)?br /> ? ? 153 = 1的三次方+5的三次方+3的三次方
解決思路:用一個(gè) for 循環(huán)在三位數(shù)中,用 / % 取出這個(gè)數(shù)的個(gè)位,十位,百位,再 if 一下,輸出這個(gè)數(shù)字;
public class id4 {public static void main(String[] args) { for(int i = 100; i < 1000; i++){int c = i % 10;int b = i / 10 % 10;int a = i / 100 % 10;if(a * a * a + b * b * b + c * c *c == i)System.out.print(i + "\t");}} }? ? 這里是用 print ,不換行;
?
2?條件運(yùn)算符嵌套
學(xué)習(xí)成績(jī)> =90 分的同學(xué)用A 表示,60-89 分之間的用B 表示,60 分以下的用C 表示。
思路:用三元表達(dá)式
3 文本文件讀寫
讀一個(gè)文件,寫到另一個(gè)文件;
import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream;public class id6 {public static void main(String[] args) {String filename = "S:\\31\\javaprj\\test1.txt";File filename_2 = new File("S:\\31\\javaprj\\test3.txt");try {//創(chuàng)建流InputStream in = new FileInputStream(filename);OutputStream out = new FileOutputStream(filename_2);try {//創(chuàng)建緩存區(qū)域讀取字節(jié)文件byte buffer[] = new byte[in.available()];//讀取字節(jié)文件in.read(buffer);//對(duì)字節(jié)進(jìn)行處理String str = new String(buffer);System.out.println(str);//向該路徑寫入內(nèi)容out.write(str.getBytes());//關(guān)閉流in.close();out.close();} catch (IOException e) {e.printStackTrace();}} catch (FileNotFoundException e1) {e1.printStackTrace();}} }?
使用FileInputStream和OutputStream類;
in.read(buffer);
? ? 讀進(jìn)buffer,buffer是字節(jié)數(shù)組;
String str = new String(buffer);
? ? 字節(jié)數(shù)組轉(zhuǎn)化為字符串;
命令行構(gòu)建和運(yùn)行結(jié)果如下;有時(shí)候會(huì)不小心打錯(cuò);
項(xiàng)目和讀寫后的文件;?
?
總結(jié)
以上是生活随笔為你收集整理的一些java基本程序图解2的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 一些java基本程序图解1
- 下一篇: Matlab画三维曲线入门