Java基礎選拔題(1)
1、素數問題:素數是除了1和本身沒有其它因子的自然數。
(1)輸出全部2位素數。
(2)判斷20034534543是不是素數;
如果是合數,那麼進行分解。合數分解格式:15 = 3 * 5
代碼:
public class number1 {
public static void main(String[] args) {
System.out.println("全部素數有:");
out:for(int i=2;i<100;i++){
for(int j=2;j<i;j++){
if(i%j==0){
continue out;
}
}
System.out.print(i+",");
}
System.out.println();
long k=200345345343L;
for(long i = 2; i<k/2; i++){
if (k%i==0){
long t=k/i;
System.out.println(k+"="+i+"*"+t);
}
}
}
}
2、填充國際象棋盤:國際象棋盤中,第1 格放1 粒米,第2 格放2 粒米,第3格放4 粒米,第4 格放8 粒米,第5 格放16粒米,……問:64個格子總共可以放多少粒米?
輸出格式:
1: 1
2: 2
3: 4
4: 8
5: 16
6: 32
……
64: 9223372036854775808
sum = 18446744073709551615
代碼:
public class number2_1 {
public static void main(String[] args) {
long a=System.currentTimeMillis(); // 獲取開始時間
String coun = "1";
String sum = "0";
for (int i = 1; i <=64; i++) {
System.out.println(i+":"+coun);
BigInteger big = new BigInteger(coun);
BigInteger max = new BigInteger(sum);
sum = big.add(max).toString();
coun = big.add(big).toString();
}
System.out.println("sum="+sum);
long b = System.currentTimeMillis(); // 獲取結束時間
System.out.println("所耗時間是:"+(b-a)+"ms");
}
}
3、文件複製:將d:\windows目錄下的全部exe文件拷貝到E:\test目錄裏。
代碼:
public class number3 {
//文件複製將D盤dos目錄下的所有exe文件拷貝到E盤test目錄下
public static void main(String[] args) throws IOException {
String fu="D:\\測試文件夾";
String cun ="E:\\測試文件夾\\";
File file=new File(fu);
File[] fulist=file.listFiles(); //獲取到列表
for(File i: fulist){
String name=i.getName();
if(! i.isDirectory()){
if((name).startsWith("txt", name.length()-3)){
name=i.getName();
FileOutputStream out =new FileOutputStream(cun+name);
FileInputStream in =new FileInputStream(i);
byte[] Buffer =new byte[1024];// 創建緩衝區
int len=in.read(Buffer); // 首先寫入一次
while (len !=-1){
out.write(Buffer,0,len);
len=in.read(Buffer);
}
out.flush();
out.close();
in.close();
}
}
}
}
}
4、文件統計:統計一篇英文文章裏每個單詞的個數。
代碼:
public class number4 {
public static void main(String[] args) throws IOException {
String url="D:\\測試文件夾\\t.txt";
FileReader in=new FileReader(url);
char[] str =new char[1024];
int len=in.read(str);
String st="";
while(len!=-1){
st+=new String(str);
len=in.read(str);
}
String[] list=st.split(" ");
for(String i:list){
int count=0;
for(String j:list){
if (i.equals(j)){
count+=1;
}
}
System.out.println(i+":"+count);
}
}
}
5、去重操作:去掉文件中的重複IP地址,統計不同IP地址的個數。
文件ips.txt內容:
192.168.234.21
192.168.234.22
192.168.234.21
192.168.234.21
運行結果如下:
public class number5 {
public static void main(String[] args) throws IOException {
String url="D:\\測試文件夾\\ip.txt";
BufferedReader in = new BufferedReader(new FileReader(url));
String s="";
HashSet<String> text=new HashSet<String>();
while(( s= in.readLine()) != null) {
text.add(s);
}
System.out.println(text.size());
}
}