java初学基础班经典练手小程序300例(飘叶寻梦整理)
(2012-07-11 22:51:44)本文转载于http://blog.sina.com.cn/s/blog_7192f33401016v43.html
一.函数
1.
*************************************************************************************************************************************
编程题:
class
{
//第二种方法:因为return是个变量,我们可以定义一个变量chr来表示return 然后返回到这个变量就行了。
}
二.数组
***********************************************************************************************************************************
1.获取一个数组中的最值???
***********************************************************************************************************************************
主函数中的写法:
public static void main(String[] args)
程序写法:
不加注释的写法:
public static int getMax(int [] arr)
加完注释的写法:
public static int getMax(int[] arr)
***********************************************************************************************************************************
2.对一个数组进行遍历?????????????????
***********************************************************************************************************************************
主函数中的调用:
int [] arr={36,23,55,65,23,45,65,32};
函数的书写:
public static void printArry(int [] arr)
***********************************************************************************************************************************
3.对数组中的位置进行置换?????????????????
***********************************************************************************************************************************
public static int swap(int []arr,int a,int b)
***********************************************************************************************************************************
4.定义一个输出语句?????????????????
***********************************************************************************************************************************
public static void sop(String str)
***********************************************************************************************************************************
5.使用选择排序法对数组进行排序?????????????????
***********************************************************************************************************************************
//选择排序
public static void sop(String str)
public static void swap(int []arr,int a,int b)
public static void printArry(int [] arr)
***********************************************************************************************************************************
6.使用冒泡排序法对数组进行排序?????????????????
***********************************************************************************************************************************
主函数调用如下:
int [] arr={36,23,55,65,23,45,65,32};
程序如下:
{
}
***********************************************************************************************************************************
7.对数组中的元素进行反转?????????????????
***********************************************************************************************************************************
程序如下:
***********************************************************************************************************************************
8.演示二分查找法????????????????
***********************************************************************************************************************************
***********************************************************************************************************************************
9.找一个数组中查找一个元素的第一次出现的位置????????????????
***********************************************************************************************************************************
***********************************************************************************************************************************
10.数组中查表法的应用--通过用户的指定星期数字,返回给用户对应的星期中文或者英文.????????????????
***********************************************************************************************************************************
class ArrayTest3
{
}
***********************************************************************************************************************************
11.对二维数组进行求和??????????????
***********************************************************************************************************************************
class
{
}
三、线程
四、集合
***********************************************************************************************************************************
1.string的一些练习??????????????
***********************************************************************************************************************************
String str = "abnbacd";
String s = str.replace("nba", "haha");
System.out.println("s="+s);
System.out.println(str);
char[] chs = str.toCharArray();//将字符串转成字符数组。
boolean b = str.contains("Demo");
System.out.println("b="+b);
boolean b1 = str.endsWith(".java");
str = "zhangsan,lisi,wangwu";
String[] names = str.split(",");
for (int i = 0; i < names.length; i++) {
System.out.println(names[i]);
}
str = "
str = str.trim();
System.out.println("-"+str+"-");
********************************************************************************************************************************
2.获取一个子串在字符串中出现的次数。"nbawernbatyunbaidfnbaghj
***********************************************************************************************************************************
package cn.itcast.api.p2.string.test;
public class StringTest2
{
public static void main(String[] args)
{
String s1 = "nbawernbatyunbaidfnbaghj
String key = "nba";
int count = getSubCount(s1, key);
System.out.println(key + ",count=" + count);
String s2 = "abcde";
s2 = reverseString(s2);
System.out.println("reverse:" + s2);
}
public static String reverseString(String str)
{
// 1,将字符串转成字符数组。
char[] chs = str.toCharArray();
reverseArrary(chs);
return new String(chs);// 通过构造器将字符数组转成字符串。
}
private static void reverseArrary(char[] chs)
{
for (int start = 0, end = chs.length - 1; start < end; start++, end--)
{
swap(chs, start, end);
}
}
private static void swap(char[] chs, int start, int end)
{
char temp = chs[start];
chs[start] = chs[end];
chs[end] = temp;
}
public static int getSubCount(String str, String key)
{
// 1,定义变量,一个是计数器,一个是记录位置。
int count = 0;
int index = 0;
// 2,调用indexOf方法获取key出现的位置。
while ((index = str.indexOf(key, index)) != -1)
{
index = index + key.length();
count++;
}
return count;
}
}
***********************************************************************************************************************************
3.获取两个字符串中最大相同子串。
* 如:"rtyuicctvoprtyu"
*
***********************************************************************************************************************************
package cn.itcast.api.p2.string.test;
public class StringTest4 {
public static void main(String[] args) {
String s1 = "rtyuicctvoprtyu";
String s2 = "cvbcctvnm";
String maxsub = getMaxSubstring(s2,s1);
System.out.println("maxsub="+maxsub);
}
public static String getMaxSubstring(String s1, String s2) {
String max,min;
max = s1.length()>s2.length()?s1:s2;
min = max.equals(s1)?s2:s1;
// System.out.println("max="+max+",,min="+min);
for(int x=0; x<min.length(); x++){
for(int y=0,z=min.length()-x; z!=min.length()+1; y++,z++){
//获取s2子串
String temp = min.substring(y,z);
// System.out.println(temp);
if(max.contains(temp)){//s1.indexOf(temp)!=-1
return temp;
}
}
}
return null;
}
}
***********************************************************************************************************************************
4,对这个字符串数组进行字典顺序的排序。
* {"aaa","abc","cba","nba","qq","zz"}??????????????
***********************************************************************************************************************************
package cn.itcast.api.p2.string.test;
public class StringTest5 {
public static void main(String[] args) {
String[] strs = {"cba","abc","nba","zz","qq","aaa"};
sortString(strs);
for (int i = 0; i < strs.length; i++) {
System.out.print(strs[i]+",");
}
}
public static void sortString(String[] strs) {
for (int i = 0; i < strs.length-1; i++) {
for (int j = i+1; j < strs.length; j++) {
if(strs[i].compareTo(strs[j])>0)
swap(strs,i,j);
}
}
}
private static void swap(String[] strs, int i, int j) {
String
strs[i] = strs[j];
strs[j] = temp;
}
public static void sort(int[] arr){
for (int i = 0; i < arr.length-1; i++) {
for (int j = i+1; j < arr.length; j++) {
if(arr[i]>arr[j]){
swap(arr,i,j);
}
}
}
}
private static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
***********************************************************************************************************************************
5. "34 9 -7 12 67 25"要求对这个字符串中的数值进行从小到大的排序,??????????????(很重要)
***********************************************************************************************************************************
package cn.itcast.api.p2.wrapper.test;
import java.util.Arrays;
public class WrapperTest2 {
private static final String SPACE = " ";
public static void main(String[] args) {
String str = "34 9 -7 12 67 25";
str = sortStringNumber(str);
System.out.println(str);
}
public static String sortStringNumber(String str) {
//1,将字符串中的数值通过指定的规则进行切割获取字符串数组。
String[] str_nums = toStringArray(str);
//2,将字符串数组转成int数组。
int[] nums = toIntArray(str_nums);
//3,对int数组排序;
sortIntArray(nums);
//4,将int数组变成字符串。
return arrayToString(nums);
}
private static String arrayToString(int[] nums) {
//1,创建字符串缓冲区。
StringBuilder sb = new StringBuilder();
for (int i = 0; i < nums.length; i++) {
if(i!=nums.length-1)
sb.append(nums[i]+SPACE);
else
sb.append(nums[i]);
}
return sb.toString();
}
private static void sortIntArray(int[] nums) {
Arrays.sort(nums);
}
private static int[] toIntArray(String[] str_nums) {
//1,先定义一个int数组。
int[] arr = new int[str_nums.length];
//2,对字符串数组进行遍历。
for (int i = 0; i < str_nums.length; i++) {
//将数组格式的字符串转成整数。存储到arr数组中。
arr[i] = Integer.parseInt(str_nums[i]);
}
return arr;
}
private static String[] toStringArray(String str) {
return str.split(SPACE);
}
}
***********************************************************************************************************************************
1.string的一些练习??????????????
***********************************************************************************************************************************
***********************************************************************************************************************************
1.string的一些练习??????????????
***********************************************************************************************************************************
五、IO操作
***********************************************************************************************************************************
1.把一个文件夹中的内容拷贝到另一个文件夹中去??????????????
***********************************************************************************************************************************
package cn.itcast.io.p3.test;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class CopyTextTest2 {
public static void main(String[] args) {
//1,定义字符输入流和字符输出流的引用。
FileReader fr = null;
FileWriter fw = null;
try {
//2,对流对象进行初始化。
fr = new FileReader("demo.txt");
fw = new FileWriter("copy_demo2.txt");
//3,定义一个数组缓冲区。用于缓冲读取到的数据。
char[] buf = new char[1024];
//4,读写操作。
int len = 0;
while((len = fr.read(buf))!=-1){
fw.write(buf,0,len);
}
} catch (Exception e) {
System.out.println(e.toString());
}finally{
if(fw!=null)
try {
fw.close();
} catch (IOException e) {
throw new RuntimeException("写入关闭失败");
}
if(fr!=null)
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
*********************************************************************************************
2.使用字节流拷贝一个MP3文件?
**********************************************************************************************
第一种方法,使用自定义数组缓冲区的方式。 (第一种方法为主)
public static void main(String[] args) throws IOException {
FileReader fr = new FileReader("c:\\0.jpg");
FileWriter fw = new FileWriter("c:\\1.jpg");
long start = System.currentTimeMillis();
copy_1();
long end = System.currentTimeMillis();
System.out.println("毫秒值:"+(end-start));
}
//自定义数组缓冲区的方式。
public static void copy_1() throws IOException {
//1,读取流对象,和mp3关联。
FileInputStream fis = new FileInputStream("C:\\0.mp3");
//2,写入流对象,明确存储mp3数据的目的。
FileOutputStream fos = new FileOutputStream("c:\\1.mp3");
//3,定义一个字节缓冲区。
byte[] buf = new byte[1024*8];
int len = 0;
while((len=fis.read(buf))!=-1){
fos.write(buf,0,len);
}
fos.close();
fis.close();
}
第二种方法:使用字节流自带缓冲区(慎用)
public static void main(String[] args) throws IOException {
FileReader fr = new FileReader("c:\\0.jpg");
FileWriter fw = new FileWriter("c:\\1.jpg");
long start = System.currentTimeMillis();
copy_2();
long end = System.currentTimeMillis();
System.out.println("毫秒值:"+(end-start));
}
public static void copy_2() throws IOException {
FileInputStream fis = new FileInputStream("C:\\0.mp3");
FileOutputStream fos = new FileOutputStream("c:\\2.mp3");
BufferedInputStream bufis = new BufferedInputStream(fis);
BufferedOutputStream bufos = new BufferedOutputStream(fos);
int by = 0;
while((by=bufis.read())!=-1){
bufos.write(by);
}
bufos.close();
bufis.close();
}
第三种方法:创建一个刚刚好的缓冲区。(不建议使用刚刚好的缓冲区,因为如果文件大的话,内存就会溢出)
public static void main(String[] args) throws IOException {
FileReader fr = new FileReader("c:\\0.jpg");
FileWriter fw = new FileWriter("c:\\1.jpg");
long start = System.currentTimeMillis();
copy_1();
long end = System.currentTimeMillis();
System.out.println("毫秒值:"+(end-start));
}
public static void copy_3() throws IOException {
FileInputStream fis = new FileInputStream("C:\\0.mp3");
FileOutputStream fos = new FileOutputStream("c:\\3.mp3");
byte[] buf = new byte[fis.available()];
fis.read(buf);
fos.write(buf);
fos.close();
fis.close();
}
第四种方法:单字节复制。
public static void main(String[] args) throws IOException {
FileReader fr = new FileReader("c:\\0.jpg");
FileWriter fw = new FileWriter("c:\\1.jpg");
long start = System.currentTimeMillis();
copy_4();
long end = System.currentTimeMillis();
System.out.println("毫秒值:"+(end-start));
}
public static void copy_4() throws IOException {
FileInputStream fis = new FileInputStream("C:\\0.mp3");
FileOutputStream fos = new FileOutputStream("c:\\4.mp3");
int by = 0;
while((by=fis.read())!=-1){
fos.write(by);
}
fos.close();
fis.close();
*********************************************************************************************
3.获取键盘录入,并把录入字符转换成大写输出出来。
********************************************************************************************
package cn.itcast.io.p3.transstream.demo;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class TransStreamDemo2 {
public static void main(String[] args) throws IOException {
简写为下面这样:
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
BufferedReader bufr = new BufferedReader(new InputStreamReader(new FileInputStream("tempfile\\fos.txt")));
BufferedWriter bufw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("tempfile\\fos1.txt")));
//频繁的读写操作。
String line = null;
while((line=bufr.readLine())!=null){
if("over".equals(line))
break;
bufw.write(line.toUpperCase());
bufw.newLine();
bufw.flush();
}
//因为是从System获取的流可以不关闭,随着系统的结束而结束。
bufw.close();
bufr.close();
}
}
*********************************************************************************************
4.练习:文件类型名过滤器????????????
********************************************************************************************
package cn.itcast.io.p1.file;
import java.io.File;
import java.io.FilenameFilter;
public class FileterBySuffix implements FilenameFilter
{
private String
public FileterBySuffix(String suffix)
{
super();
this.suffix = suffix;
}
@Override
public boolean accept(File dir, String name)
{
return name.endsWith(suffix);
}
}
*********************************************************************************************
5.练习:定义一个功能用于记录住软件运行的次数,如果运行次数大于5次。不要在运行????????????
********************************************************************************************
package cn.itcast.io.p5.properties;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
public class PropertiesTest {
public static void main(String[] args) throws IOException {
if(countDemo()){
//运行程序代码。
System.out.println("运行程序");
}else{
System.out.println("试用次数已到,请注册!给钱!");
}
}
public static boolean countDemo() throws IOException{
Properties prop = new Properties();
int count = 0;
//配置文件。
File confile = new File("config.txt");
if(!confile.exists())
confile.createNewFile();
FileInputStream fis = new FileInputStream(confile);
//将流中的数据加载到prop中。
prop.load(fis);
//获取配置文件中的次数。
String value = prop.getProperty("count");
if(value!=null){
count = Integer.parseInt(value);
if(count>=5){
// System.out.println("试用次数已到,请注册!给钱!");
return false;
}
}
count++;
System.out.println("运行"+count+"次");
//将具体的键和次数存储到集合中。
prop.setProperty("count", String.valueOf(count));//count+"";
//将集合中的数据写入到文件中持久化。
FileOutputStream fos = new FileOutputStream(confile);
prop.store(fos, "");
fos.close();
fis.close();
return true;
}
}
*********************************************************************************************
6.练习:获取指定目录中的所有内容(包含子目录中的内容)????????????
********************************************************************************************
package cn.itcast.io.p3.file.test;
import java.io.File;
public class FileTest {
public static void main(String[] args) {
File dir = new File("e:\");
showDir(dir,0);
}
//递归。
public static void showDir(File dir,int count){
System.out.println(getSpace(count)+dir.getName());
count++;
File[] files = dir.listFiles();
// if(files!=null)//健壮性判断。
for(File f : files){
if(f.isDirectory()){
showDir(f,count);
}
else
System.out.println(getSpace(count)+f.getName());
}
}
private static String getSpace(int count) {
StringBuilder sb = new StringBuilder();
for(int x=0; x<count; x++){
sb.append("|--");
}
return sb.toString();
}
}
*********************************************************************************************
练习:获取指定目录中的目录????????????
********************************************************************************************
public static void main(String[] args)
{
File b=new File("c:\");
File[] files=b.listFiles();
for (File f : files)
{
System.out.println(f);
}
}
*********************************************************************************************
7.练习:删除一个带内容的文件夹????????????
********************************************************************************************
package cn.itcast.io.p3.file.test;
import java.io.File;
public class FileTest2 {
public static void main(String[] args) {
File dir = new File("e:\\demodir");
removeDir(dir);
}
public static void removeDir(File dir){
File[] files = dir.listFiles();
for(File file : files){
if(file.isDirectory()){
removeDir(file);
}else{
System.out.println(file+":"+file.delete());
}
}
System.out.println(dir+":"+dir.delete());
}
}
*********************************************************************************************
8.对指定目录中的所有(包含子目录)的Java文件的绝对路径写入到一个文本文件中????????????
********************************************************************************************
package cn.itcast.io.p6.test;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Test1
{
public static void main(String[] args) throws IOException
{
File dir = new File("E:\\软件开发学习\\传智播客java征途");
FilenameFilter filter = new FilenameFilter()
{
@Override
public boolean accept(File dir, String name)
{
return name.endsWith(".avi");
}
};
List<File> list = new ArrayList<File>();
// 使用递归,过滤并存储。
listAllJavaFile(dir, filter, list);
// 创建目的地文件。
File file = new File(dir, "传智播客java征途视频.txt");
write2File(list, file);
}
// 1.定义一个功能,递归
public static void listAllJavaFile(File dir, FilenameFilter filter,
List<File> list)
{
File[] files = dir.listFiles();
if (files != null)
{
for (File file : files)
{
if (file.isDirectory())// 如果是目录就递归。
{
listAllJavaFile(file, filter, list);
}
else if (filter.accept(dir, file.getName()))// 使用过滤器对指定的目的和文件名进行过滤,符合条件进行存储。
{
list.add(file);
}
}
}
}
private static void write2File(List<File> list, File dest)
{
BufferedWriter bufw =null;
try
{
bufw=new BufferedWriter(new FileWriter(dest));
// 遍历集合
for (File file : list)
{
bufw.write(file.getAbsolutePath());
bufw.newLine();
bufw.flush();
}
}
catch (Exception e)
{
// TODO: handle exception
}finally
{
if(bufw!=null)
{
try
{
bufw.close();
}
catch (IOException e)
{
new RuntimeException("关闭失败");
}
}
}
}
}
*********************************************************************************************
9..需求:将一个段文字数据写入到硬盘上.????????????
********************************************************************************************
public static void main(String[] args) throws IOException
{
FileWriter fw=new FileWriter("g:\\iotest.txt");
fw.write("你好");
fw.flush();
fw.close();
}
来点高级的 ,需求:第一个是加入换行符号,再一个就是接着往这个文件夹里面写东西,而不是覆盖原来的内容。
1,编写程序,判断给定的某个年份是否是闰年。
import java.util.Scanner;
class Bissextile{
}
2,给定一个百分制的分数,输出相应的等级。
import java.util.Scanner;
class Mark{
}
3,编写程序求 1+3+5+7+……+99 的和值。
class he{
}
4、利用for循环打印 9*9
1*1=1
1*2=2
1*3=3
1*4=4
1*5=5
1*6=6
1*7=7
1*8=8
1*9=9
//循环嵌套,打印九九乘法表
public class NineNine{
}
6、输出所有的水仙花数,把谓水仙花数是指一个数3位数,其各各位数字立方和等于其本身,
class DafodilNumber{
}
7、求
import java.util.Scanner;
class Multinomial{
}
8、求 2/1+3/2+5/3+8/5+13/8.....前20项之和?
class Sum{
}
9、利用程序输出如下图形:
class Asterisk{
}
11、计算圆周率
class Pi {
}
输出结果为pi = 3.1415926525880504,应该不精确
12、输入一个数据n,计算斐波那契数列(Fibonacci)的第n个值
//计算斐波那契数列(Fibonacci)的第n个值
public class Fibonacci{
}
//计算斐波那契数列(Fibonacci)的第n个值
//并把整个数列打印出来
public class FibonacciPrint{
}
13、求1-1/3+1/5-1/7+1/9......的值。
15、在屏幕上打印出n行的金字塔图案,如,若n=5,则图案如下:
//打印金字塔图案
public class PrintStar{
}
16、歌德巴赫猜想,任何一个大于六的偶数可以拆分成两个质数的和
//任何一个大于六的偶数可以拆分成两个质数的和
//打印出所有的可能
public class Gedebahe{
第4章 数组
1. 定义一个int型的一维数组,包含10个元素,分别赋一些随机整数,然后求出所有元素的最大值,
最小值,平均值,和值,并输出出来。
class ArrayNumber{
}
2.定义一个int型的一维数组,包含10个元素,分别赋值为1~10, 然后将数组中的元素都向前移一个位置,
即,a[0]=a[1],a[1]=a[2],…最后一个元素的值是原来第一个元素的值,然后输出这个数组。
3. 定义一个int型的一维数组,包含40个元素,用来存储每个学员的成绩,循环产生40个0~100之间的随机整数,
将它们存储到一维数组中,然后统计成绩低于平均分的学员的人数,并输出出来。
4. (选做)承上题,将这40个成绩按照从高到低的顺序输出出来。
5,(选做)编写程序,将一个数组中的元素倒排过来。例如原数组为1,2,3,4,5;则倒排后数组中的值
为5,4,3,2,1。
6,要求定义一个int型数组a,包含100个元素,保存100个随机的4位数。再定义一个
class Remain{
}
7,定义一个20*5的二维数组,用来存储某班级20位学员的5门课的成绩;这5门课
class Student{
}//未完成
import java.util.Scanner;
class NinePalace{
}
9,求一个3*3矩阵对角线元素之和
10,打印杨辉三角
11. 约梭芬杀人法
11_2、用数组实现约瑟夫出圈问题。 n个人排成一圈,从第一个人开始报数,从1开始报,报到m的人出圈,剩下的人继续开始从1报数,直到所有的人都出圈为止。对于给定的n,m,求出所有人的出圈顺序。
12. 判断随机整数是否是素数
产生100个0-999之间的随机整数,然后判断这100个随机整数哪些是素数,哪些不是?
public class PrimeTest{
}
冒泡排序法:
//按从大到小的排序
int tmp = a[0];
for (int i=0; i < a.length; i++){
}