【转】java初学基础班经典练手小程序300例(飘叶寻梦整理)

一.函数
1.
*************************************************************************************************************************************
编程题:
 定义一个功能,完成对考试成绩的等级划分。
 90~100 A 优秀
 80~89 B 良好
 70~79 C 中等
 60~69 D 及格
 60以下 E 不及格

class  Test04
{
 public static void main(String[] args)
 {
  char level =getLevel(78);
  System.out.println("level="+level);
 }

//第二种方法:因为return是个变量,我们可以定义一个变量chr来表示return 然后返回到这个变量就行了。

   public static char getLevel(int num)
  {

   char chr;
   if(num>=90 && num<=100)
   chr= 'a';
  else if(num >=80 && num<=89)
   chr= 'b';
  else if(num >=70 && num<=79)
   chr= 'c';
  else if(num >=60 && num<=69)
   chr= 'd';
  else
   chr='e';
   return chr;
  }
     
}

 


二.数组

***********************************************************************************************************************************
1.获取一个数组中的最值???
***********************************************************************************************************************************


 
 //先遍历数组,然后再这个遍历里面加上条件语句,然后再找出最大值,遍历一般都用for语句,这个以后记着了

主函数中的写法:

public static void main(String[] args)
 {
  int [] arr={22,23,34,56,76,23};
  int max=getMax(arr);
  System.out.println("max="+max);
 }

程序写法:

不加注释的写法:
public static int getMax(int [] arr)
 {
  int max =arr [0];
  for (int x=1;x<arr.length;x++ )
  {
   if (arr[x]>max)
   {
    max =arr[x];
   }  
  }
   return max;
 }

加完注释的写法:
public static int getMax(int[] arr)
 {
  //1,定义变量用于记录住每次比较完较大的值,初始化为数组中的任意一个元素。
  int max = arr[0];

  //2,对数组元素进行遍历。
  for(int x=1; x<arr.length; x++)
  {
   //3,将遍历到的元素和变量中存储的元素进行比较。将大的值存储到变量中。
   if(arr[x]>max)
    max = arr[x];
  }
  return max;
 }

 

***********************************************************************************************************************************
2.对一个数组进行遍历?????????????????
***********************************************************************************************************************************
主函数中的调用:
int [] arr={36,23,55,65,23,45,65,32};
  printArry(arr);

函数的书写:
public static void printArry(int [] arr)
 {
   for (int x=0;x<arr.length ;x++ )
  {
   if (x!=arr.length-1)
   System.out.print(arr[x]+".");
   else
   System.out.print(arr[x]);
  }
   
 }

***********************************************************************************************************************************
3.对数组中的位置进行置换?????????????????
***********************************************************************************************************************************
public static int swap(int []arr,int a,int b)
 {
  int temp=arr[a];
  arr[a]=arr[b];
  arr[b]=temp;
 }

***********************************************************************************************************************************
4.定义一个输出语句?????????????????
***********************************************************************************************************************************
public static void sop(String str)
 {
  System.out.println(str);
 }

***********************************************************************************************************************************
5.使用选择排序法对数组进行排序?????????????????
***********************************************************************************************************************************
//选择排序
   
 

    public static void selectSort(int [] arr)
 {
  for (int x=0;x<arr.length-1 ; x++)
  {
   for(int y=x+1;y<arr.length;y++)
   {
    if (arr[x]>arr[y]) //假如把这个>号换个方向,那么它的排序后的顺序就换了。
    {
     swap(arr,x,y);
    }
   }
  }
 }

 

public static void sop(String str)
 {
  System.out.println(str);
 }

 

public static void swap(int []arr,int a,int b)
 {
  int temp=arr[a];
  arr[a]=arr[b];
  arr[b]=temp;

 }

 


public static void printArry(int [] arr)
 {
   for (int x=0;x<arr.length ;x++ )
  {
   if (x!=arr.length-1)
   System.out.print(arr[x]+".");
   else
   System.out.println(arr[x]);
  }
   
 }

***********************************************************************************************************************************
6.使用冒泡排序法对数组进行排序?????????????????
***********************************************************************************************************************************

主函数调用如下:
int [] arr={36,23,55,65,23,45,65,32};
  sop("排序前");
  printArry(arr);
  sop("排序后");
  bubbleSort(arr);
  printArry(arr);

 


程序如下:
 public static void bubbleSort(int[] arr)
{
  for (int x=0;x<arr.length-1 ;x++ )
 {
  for (int y=0;y<arr.length-1-x ;y++ )
  {
   if (arr[y]<arr[y+1])
   {
    swap(arr,y,y+1);
   }
   
  }
 }
}
***********************************************************************************************************************************
7.对数组中的元素进行反转?????????????????
***********************************************************************************************************************************


程序如下:
  public static void reverseArry(int[] arr)
  {
   for (int start=0,end=arr.length-1 ;start<end; start++,end--)
   {
    swap(arr,star,end);
   }

  }

 

***********************************************************************************************************************************
8.演示二分查找法????????????????
***********************************************************************************************************************************
 
 public static int binarySearch(int[] arr,int key)
 {
  //1,需要定义三个变量,用于记录住角标的变化。
  int min,max,mid;
  min = 0;
  max = arr.length-1;
  //只要min和max之间有距离,就有了折半的可能,而且有可能折半多次,使用while循环。。
  while(min<=max)
  {
   //获取中间角标。
   mid = (max+min)/2;    //mid = (max+min)>>1;

   //获取中间角标上的元素和key进行比较。
   //来确定min和max的新值。或者叫做,确定新的查找范围。
   if(key>arr[mid])
    min = mid + 1;
   else if(key<arr[mid])
    max = mid - 1;
   else
    return mid;
  }
  return -1;
 }


***********************************************************************************************************************************
9.找一个数组中查找一个元素的第一次出现的位置????????????????
***********************************************************************************************************************************


 public static int getIndex(int[] arr,int key)
 {
  for(int x=0; x<arr.length; x++)
  {
   if(arr[x]==key)
   return x;
  }
  return -1;
 }


***********************************************************************************************************************************
10.数组中查表法的应用--通过用户的指定星期数字,返回给用户对应的星期中文或者英文.????????????????
***********************************************************************************************************************************


class ArrayTest3
{
 public static void main(String[] args)
 {

  String week = getWeekText(8);//这句话输出的结果是星期几,这个输出的是字符串的类型的,所以应该使用字符串来表示,不能够使用int来表示。
  System.out.println("week="+week);
 }

 
 public static String getWeekText(int num)
 {

  if(num>7 || num<1)
  {
   return num+"没有对应的星期";
  }
  String[] weeks = {"","星期一","星期二","星期三","星期四","星期五","星期六","星期日"};//写一个包含星期的数组,这个数组的下标一定要是有顺序的。

  return weeks[num];
 }
}

***********************************************************************************************************************************
11.对二维数组进行求和??????????????
***********************************************************************************************************************************

class  Arry2Test
{
 public static void main(String[] args)
 { 
  int arr[] []={{22,33,12,32},{23,54,12,11},{65,87,89,23}}
  int sum=0;
  //先遍历数组,然后再求和
  for (int x=0;x<arr.length;x++)
  {
   for (int y=0;y<arr[x].length ;y++)
   {
    sum=sum+arr[x][y];
   }
  }
  System.out.println("sum="+sum)
 }
}

 

 

三、线程

 

 

 

四、集合

***********************************************************************************************************************************

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 = "     ab   c     ";

str = str.trim();

System.out.println("-"+str+"-");

 

 

********************************************************************************************************************************

2.获取一个子串在字符串中出现的次数。"nbawernbatyunbaidfnbaghjnba" nba出现了几次??????????????+1

***********************************************************************************************************************************

 

package cn.itcast.api.p2.string.test;

 

public class StringTest2

{

 

public static void main(String[] args)

{

 

String s1 = "nbawernbatyunbaidfnbaghjnba";

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"

*         "cvbcctvnm"  最大相同是cctv?????????????? +1

***********************************************************************************************************************************

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  temp = strs[i];

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  suffix;

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,编写程序,判断给定的某个年份是否是闰年。

      闰年的判断规则如下:

      (1)若某个年份能被4整除但不能被100整除,则是闰年。

      (2)若某个年份能被400整除,则也是闰年。

 

import java.util.Scanner;

class Bissextile{

    public static void main(String[] arge){

        System.out.print("请输入年份");

    int year;    //定义输入的年份名字为“year”

    Scanner scanner = new Scanner(System.in);

    year = scanner.nextInt();

    if (year<0||year>3000){

        System.out.println("年份有误,程序退出!");

        System.exit(0);

        }

    if ((year%4==0)&&(year0!=0)||(year@0==0))

        System.out.println(year+" is bissextile");

    else

        System.out.println(year+" is not bissextile ");

    }

}

 

 

 

2,给定一个百分制的分数,输出相应的等级。

        90分以上        A级

        80~89          B级

        70~79          C级

        60~69          D级

        60分以下        E级

 

import java.util.Scanner;

class Mark{

    public static void main(String[] args){

        System.out.println("请输入一个分数");

        //定义输入的分数为“mark”,且分数会有小数

        double mark;

        Scanner scanner = new Scanner(System.in);

        mark = scanner.nextDouble();

 

        //判断是否有输入错误。

        if(mark<0||mark>100){

           System.out.println("输入有误! ");

           System.exit(0);

        }

       

        if (mark>=90) System.out.println("this mark is grade \'A\' ");

        else if (mark>=80) System.out.println("this mark is grade \'B\' ");

        else if (mark>=70) System.out.println("this mark is grade \'C\' ");

        else if (mark>=60) System.out.println("this mark is grade \'D\' ");

        else  System.out.println("this mark is grade \'E\' ");

    }

}

 

 

 

3,编写程序求 1+3+5+7+……+99 的和值。

 

class he{

    public static void main(String[] args){

        int number = 1;  //初始值1,以后再+2递增上去

        int sum = 0;

        for ( ; number <100; number+=2 ){ sum += number; }

        System.out.println("1+3+5+7+……+99= " +sum);

    }

}

 

 

 

4、利用for循环打印 9*9  表?

1*1=1

1*2=2  2*2=4

1*3=3  2*3=6  3*3=9

1*4=4  2*4=8  3*4=12  4*4=16

1*5=5  2*5=10  3*5=15  4*5=20  5*5=25

1*6=6  2*6=12  3*6=18  4*6=24  5*6=30  6*6=36

1*7=7  2*7=14  3*7=21  4*7=28  5*7=35  6*7=42  7*7=49

1*8=8  2*8=16  3*8=24  4*8=32  5*8=40  6*8=48  7*8=56  8*8=64

1*9=9  2*9=18  3*9=27  4*9=36  5*9=45  6*9=54  7*9=63  8*9=72  9*9=81

 

//循环嵌套,打印九九乘法表

public class NineNine{

    public static void main(String[]args){

    System.out.println();

    for (int j=1;j<10;j++){

        for(int k=1;k<10;k++) {   //老师的做法,判断语句里的 k<=j,省去下列的if语句。

            if (k>j) break;       //此处用 continue也可以,只是效率低一点

            System.out.print(" "+k+"X"+j+"="+j*k);

         }

        System.out.println();

        }

    }

}

 

 

 

 

6、输出所有的水仙花数,把谓水仙花数是指一个数3位数,其各各位数字立方和等于其本身,

   例如: 153 = 1*1*1 + 3*3*3 + 5*5*5 

 

class DafodilNumber{

    public static void main(String[] args){

        System.out.println("以下是所有的水仙花数");

    int number = 100;     // 由于水仙花数是三位数,故由100开始算起

 

    int i, j, k;     // i  j  k  分别为number 的百位、十位、个位

    for (int sum; number<1000; number++){

        i=number/100;  j=(number-i*100)/10;  k=number-i*100-j*10;

        sum=i*i*i+j*j*j+k*k*k;

        if (sum==number) System.out.println(number+" is a dafodil number! ");

        }

    }

}

 

 

 

7、求  a+aa+aaa+.......+aaaaaaaaa=?

      其中a为1至9之中的一个数,项数也要可以指定。

 

import java.util.Scanner;

class Multinomial{

    public static void main(String[] args){

        int  a;      //定义输入的 a

        int  howMany;   //定义最后的一项有多少个数字

        Scanner scanner = new Scanner(System.in);

            System.out.println("请输入一个 1~9 的 a 值");

        a = scanner.nextInt();

            System.out.println("请问要相加多少项?");

        howMany = scanner.nextInt();

        int sum=0;

        int a1=a;  // 用来保存 a 的初始值

        for (int i=1; i<=howMany; i++){

            sum+= a;

            a = 10*a +a1;   // 这表示a 的下一项

        // 每次 a 的下一项都等于前一项*10,再加上刚输入时的 a ;注意,这时的 a 已经变化了。

            }

        System.out.println("sum="+sum);

    }

}

 

 

 

8、求 2/1+3/2+5/3+8/5+13/8.....前20项之和?

 

class Sum{

    public static void main(Sting[] args){

        double sum=0;

        double fenZi=2.0, fenMu=1.0;    //初始的分子 (fenZi)=2,分母(fenMu)=1

        for(int i=1; i<=20; i++){

            sum += fenZi / fenMu ;

            fenMu = fenZi;           //下一项的分母 = 上一项的分子

            fenZi += fenMu;         //下一项的分子 = 上一项的分子加分母

        }

        System.out.println("sum= "sum);

    }

}

 

 

 

9、利用程序输出如下图形:

   *

   * * *

   * * * * *

   * * * * * * *

   * * * * *

   * * *

   *

 

class Asterisk{

    public static void main(String[] args){

        for (int i=1; i<=13; i+=2){

            for(int j=1; j<=i && i+j<= 14; j++){System.out.print("* ");}

            System.out.println();  // 换行

        }

    }

}

 

 

 

11、计算圆周率

  PI=4-4/3+4/5-4/7.......

  打印出第一个大于 3.1415小于 3.1416的值

 

class Pi {

    public static void main(String[] args){

        double pi =0;  //定义初始值

        double fenZi = 4;    //分子为4

        double fenMu = 1;  //第一个4,可看作分母为1 的分式,以后的分母每次递增2

        for (int i = 0; i < 1000000000; i++){ //运行老久,减少循环次数会快很多,只是精确度小些

            pi += (fenZi/fenMu) ;

            fenZi *= -1.0;    //每项分子的变化是+4,-4,+4,-4 ....

            fenMu += 2.0;    //分母的变化是1,3,5,7, ....   每项递加2

            }

        System.out.println(pi);

    }

}

输出结果为pi = 3.1415926525880504,应该不精确

 

 

12、输入一个数据n,计算斐波那契数列(Fibonacci)的第n个值

  1  1  2  3  5  8  13  21  34

  规律:一个数等于前两个数之和

//计算斐波那契数列(Fibonacci)的第n个值

public class Fibonacci{

    public static void main(String args[]){

        int n = Integer.parseInt(args[0]);

        int n1 = 1;//第一个数

        int n2 = 1;//第二个数

        int sum = 0;//和

        if(n<=0){

            System.out.println("参数错误!");

            return;

        }

        if(n<=2){

            sum = 1;           

        }else{

            for(int i=3;i<=n;i++){

                sum = n1+n2;

                n1 = n2;

                n2 = sum;

            }

        }

        System.out.println(sum);

    }

}

 

 

//计算斐波那契数列(Fibonacci)的第n个值

//并把整个数列打印出来

public class FibonacciPrint{

    public static void main(String args[]){

        int n = Integer.parseInt(args[0]);

        FibonacciPrint t = new FibonacciPrint();

        for(int i=1;i<=n;i++){

            t.print(i);

        }

    }

    public void print(int n){

        int n1 = 1;//第一个数

        int n2 = 1;//第二个数

        int sum = 0;//和

        if(n<=0){

            System.out.println("参数错误!");

            return;

        }

        if(n<=2){

            sum = 1;           

        }else{

            for(int i=3;i<=n;i++){

                sum = n1+n2;

                n1 = n2;

                n2 = sum;

            }

        }

        System.out.println(sum);

    }

}

 

13、求1-1/3+1/5-1/7+1/9......的值。

  a,求出前50项和值。

  b,求出最后一项绝对值小于1e-5的和值。

 

 

 

15、在屏幕上打印出n行的金字塔图案,如,若n=5,则图案如下:

        *

       ***

      *****

     *******

    *********

 

//打印金字塔图案

public class PrintStar{

    public static void main(String args[]){

        int col = Integer.parseInt(args[0]);

        for(int i=1;i<=col;i++){//i表示行数

            //打印空格

            for(int k=0;k<col-i;k++){

                System.out.print(" ");

            }

            //打印星星

            for(int m=0;m<2*i-1;m++){

                System.out.print("*");

            }

            System.out.println();

        }

    }

}

 

16、歌德巴赫猜想,任何一个大于六的偶数可以拆分成两个质数的和

  打印出所有的可能

 

//任何一个大于六的偶数可以拆分成两个质数的和

//打印出所有的可能

public class Gedebahe{

    public static void main(String args[]){

        int num = Integer.parseInt(args[0]);

        if(num<=6){

            System.out.println("参数错误!");

            return;

        }

        if(num%2!=0){

            System.out.println("参数错误!");

            return;

        }

        Gedebahe g = new Gedebahe();

        //1不是质数,2是偶数,因此从3开始循环

        for(int i=3;i<=num/2;i++){

            if(i%2==0){//如果为偶数,退出本次循环

                continue;

            }

            //当i与num-i都为质数时,满足条件,打印

            if(g.isPrime(i) && g.isPrime(num-i)){

                System.out.println(i+" + "+(num-i)+" = "+num);

            }       

        }

    }

 

 

 

 

 

 

 

 

 

 

 

 

 

4章 数组

1. 定义一个int型的一维数组,包含10个元素,分别赋一些随机整数,然后求出所有元素的最大值,

最小值,平均值,和值,并输出出来。

 

class ArrayNumber{

    public static void main(String[] args){

        int[] arrayNumber;

        arrayNumber = new int[10];

    System.out.println("以下是随机的10个整数:");

        // 填入随机的 10个整数

        for (int i =0; i<arrayNumber.length; i++){

            arrayNumber[i] = (int)(100*Math.random());

            System.out.print(arrayNumber[i]+" ");

            }

        System.out.println();

        int max = arrayNumber[0];

        int min = arrayNumber[0];

        int sum = 0;

        for (int i =0; i<arrayNumber.length; i++){

            if(max < arrayNumber[i])

                max = arrayNumber[i];  //求最大值

            if(min > arrayNumber[i])

                min = arrayNumber[i];   //求最小值

            sum += arrayNumber[i];

            }

    System.out.println("其中Max="+max+",Min="+min+",Sum="+sum+",Avg="+sum/10.0);

    }

}

 

 

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位数。再定义一个

   int型数组b,包含10个元素。统计a数组中的元素对10求余等于0的个数,保存

   到b[0]中;对10求余等于1的个数,保存到b[1]中,……依此类推。

 

class Remain{

    public  static void main( String[] args){

        int[] a = new int[100];

 

        //保存100个随机4位数到 a 中

        for (int i = 0;  i < a.length;  i++){

            a[i] = (int) (1000*Math.random());

        }

 

        //统计 a 数组中的元素对 10 求余的各个的数目

        int[] b = new int[10];

        int k,sum;

        for (int j = 0;  j < b.length;  j++){

            for (k=0,sum=0;  k < a.length;  k++){

                if ((a[k])==j) sum++;

            }

            b[j] = sum;

            System.out.printf("b[%d]=%d\n",j,b[j]);

        }

    }

}

 

 

7,定义一个20*5的二维数组,用来存储某班级20位学员的5门课的成绩;这5门课

   按存储顺序依次为:core C++,coreJava,Servlet,JSP和EJB。

   (1)循环给二维数组的每一个元素赋0~100之间的随机整数。

   (2)按照列表的方式输出这些学员的每门课程的成绩。

   (3)要求编写程序求每个学员的总分,将其保留在另外一个一维数组中。

   (4)要求编写程序求所有学员的某门课程的平均分。

 

class Student{

    public static void main(String[] args ){

        int[][] mark = new int[20][5];

        // 给学生赋分数值,随机生成

        for ( int i = 0;  )

    }

}//未完成

 

 

 8,完成九宫格程序

    在井字形的格局中(只能是奇数格局),放入数字(数字由),使每行每列以及斜角线的和都相等

 

    经验规则:从 1 开始按顺序逐个填写; 1  放在第一行的中间位置;下一个数往右上角45度处填写;

        如果单边越界则按头尾相接地填;如果有填写冲突,则填到刚才位置的底下一格;

        如果有两边越界,则填到刚才位置的底下一格。

 

    个人认为,可以先把最中间的数填到九宫格的最中间位置;再按上面的规则逐个填写,而且

        填的时候还可以把头尾对应的数填到对应的格子中。(第 n 个值跟倒数第 n 个值对应,格局上以最中

        间格为轴心对应)

        这样就可以同时填两个数,效率比之前更高;其正确性有待数学论证(但多次实验之后都没发现有错)。

    九宫格的 1 至少还可以填在另外的三个位置,只是接下来的填写顺序需要相应改变;

    再根据九宫格的对称性,至少可以有8种不同的填写方式

 

import java.util.Scanner;

class NinePalace{

    public static void main(String[] args){

        // 定义 N 为九宫格的行列数,需要输入

        System.out.println("请输入九宫格的行列规模(只能是奇数的)");

        Scanner n = new Scanner(System.in);

        int N;

 

        //判断格局是否奇数 (可判断出偶数、负数 及小数)

        double d;

        while (true){

            d = n.nextDouble();

            N = (int)d;

            if ((d-N)>1.0E-4||N%2==0||N<0)

                {System.out.println("输入出错,格局只能是正奇数。请重新输入");}

            else break;

        }

 

        //老师的九宫格填写方法

        int[][] result = new int[N][N];   //定义保存九宫格的数组

        int row = 0; //行 初始位置

        int col = N/2; //列 初始位置,因为列由0开始,故N/2是中间位置

        for (int i=1;  i<=N*N; i++){

            result [row][col] = i;

            row--;

            col++;

            if (row<0&&col>=N){col--;row+=2;} //行列都越界

            else if (row<0){ row = N-1;}   //行越界

            else if (col>=N){col = 0;}  //列越界

            else if (result[row][col] != 0){col--;row+=2;}  //有冲突

        }

 

        //打印出九宫格

        for (int i=0;  i<N;  i++){

            for(int j=0;  j<N; j++){System.out.print(result[i][j]+"\t");}

            System.out.println();

        }

 

        //我个人的填格方式

        int[][] result2 = new int[N][N];  //为免冲突,重新 new 一个数组

        result2[N/2][N/2] = (N*N+1)/2;  //先把中间值赋予中间位置

        row = 0;   //定义行及列的初始赋值位置。之前赋值的for对两个值有影响,故需重新定位

        col = N/2;

        for (int i=1; i<=N*N/2; i++){

            result2[row][col] = i;

            //下面这句是把跟 i 对应的值放到格局对应的位置上

            result2[N-row-1][N-col-1] = N*N+1-i;

            row--;

            col++;

            if (row<0){ row = N-1;}   //行越界

            else if (col>=N){col = 0;}  //列越界

            else if (result2[row][col] != 0){col--;row+=2;}  //有冲突

            //这方法不可能出现行列两边都越界的情况,详情需要数学论证

        }

 

        System.out.println();

        //再次打印出九宫格,以对比验证

        for (int i=0;  i<N;  i++){

            for(int j=0;  j<N; j++){System.out.print(result2[i][j]+"\t");}

            System.out.println();

        }

 

    }

}

 

 

 

 

 

9,求一个3*3矩阵对角线元素之和 

 

 

10,打印杨辉三角

 

 

11. 约梭芬杀人法

   把犯人围成一圈,每次从固定位置开始算起,杀掉第7个人,直到剩下最后一个。

 

11_2、用数组实现约瑟夫出圈问题。 n个人排成一圈,从第一个人开始报数,从1开始报,报到m的人出圈,剩下的人继续开始从1报数,直到所有的人都出圈为止。对于给定的n,m,求出所有人的出圈顺序。

 

 

 

12. 判断随机整数是否是素数

产生100个0-999之间的随机整数,然后判断这100个随机整数哪些是素数,哪些不是?

 

public class PrimeTest{

    public static void main(String args[]){

        for(int i=0;i<100;i++){

            int num = (int)(Math.random()*1000);

            PrimeTest t = new PrimeTest();

            if(t.isPrime(num)){

                System.out.println(num+" 是素数!");

            }else{

                System.out.println(num+" 不是素数!");

            }

            System.out.println();

        }

    }

    public boolean isPrime(int num){

        for(int i=2;i<=num/2;i++){

            if(num%i==0){

                System.out.println(num+"第一个被"+i+"整除!");

                return false;

            }

        }

        return true;

    }

}

 

 

 

 

 

 

 

冒泡排序法:

//按从大到小的排序

int tmp = a[0];

for (int i=0; i < a.length; i++){

    for (int j=0; j < a.length - i -1; j++){

        if (a[j] < a[j+1]) {

            tmp = a[j];

            a[j] = a[j+1];

            a[j+1] = tmp;

        }

    }

}

 

转载于:https://www.cnblogs.com/royalisme/p/4785920.html

本书内容包括java语言概述、 eclipse开发工具、 java语言基础、 流程控制、 数组及其常用操作、 面向对象入门、 面向对象进阶、 字符串与包装类、 java集合类框架、 常用数学工具类、 错误处理、 输入/输出、 枚举类型与泛型、 swing入门、 多线程、 网络通信和数据库操作。   本书所精选的实都是一线开发人员在实际项目中所积累的,并进行了技术上的解析,给出了详细的实现过程。读者通过对本书的学习,能够提高开发的能力。    本书提供了大量的源程序、素材,提供了相关的模块库、案库、素材库、题库等多种形式辅助学习资料,还提供迅速及时的微博、qq、论坛等技术支持。    本书内容详尽,实丰富,非常适合作为零基础学习人员的学习用书和大中专院校师生的学习教材,也适合作为相关培训机构的师生和软件开发人员的参考资料。 《java经典编程300》 第1章 java语言概述   实001 输出“hello world”   实002 输出控制台传递的参数   实003 输出由“*”组成的三角形   实004 输出符号表情 第2章 eclipse开发工具   实005 下载并运行eclipse 工具   实006 为eclipse安装汉化包   实007 使用eclipse注释代码   实008 使用eclipse格式化代码   实009 安装windowbuilder插件   实010 开发计算器界面 第3章 java语言基础   实011 输出错误信息与调试信息   实012 从控制台接收输入字符   实013 重定向输出流实现程序日志   实014 自动类型换与强制类型换   实015 加密可以这样简单(位运算)   实016 用三元运算符判断奇数和偶数 .  实017 不用乘法运算符实现2×16   实018 实现两个变量的互换(不借助第3个变量)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值