1. 程式人生 > >50道JAVA基礎程式設計練習題

50道JAVA基礎程式設計練習題

【程式1】

題目:古典問題:有一對兔子,從出生後第3個月起每個月都生一對兔子,小兔子長到第三個月後每個月又生一對兔子,假如兔子都不死,問每個月的兔子對數為多少?

程式分析: 兔子的規律為數列1,1,2,3,5,8,13,21....

public class Prog1{

public static void main(String[] args){

int n = 10;

System.out.println(""+n+"個月兔子總數為"+fun(n));

}

private static int fun(int n){

if(n==1 || n==2)

   return 1;

else

   return fun(n-1)+fun(n-2);

}

}

【程式2】

題目:判斷101-200之間有多少個素數,並輸出所有素數。

程式分析:判斷素數的方法:用一個數分別去除2到sqrt(這個數),如果能被整除,則表明此數不是素數,反之是素數。

public class Prog2{

public static void main(String[] args){

int m = 1;

int n = 1000;

int count = 0;

//統計素數個數

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

if(isPrime(i)){

count++;

System.out.print(i+" ");

if(count%10==0){

System.out.println();

}

}

}

System.out.println();

System.out.println("在"+m+"和"+n+"之間共有"+count+"個素數");

}

//判斷素數

private static boolean isPrime(int n){

boolean flag = true;

if(n==1)

  flag = false;

else{

for(int i=2;i<=Math.sqrt(n);i++){

if((n%i)==0 || n==1){

flag = false;

break;

}

 else

   flag = true;

  }

}

return flag;

}

}

【程式3】

題目:打印出所有的"水仙花數",所謂"水仙花數"是指一個三位數,其各位數字立方和等於該數本身。例如:153是一個"水仙花數",因為153=1的三次方+5的三次方+3的三次方。

程式分析:利用for迴圈控制100-999個數,每個數分解出個位,十位,百位。

public class Prog3{

public static void main(String[] args){

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

if(isLotus(i))

   System.out.print(i+" ");

}

System.out.println();

}

//判斷水仙花數

private static boolean isLotus(int lotus){

int m = 0;

int n = lotus;

int sum = 0;

m = n/100;

n  -= m*100;

sum = m*m*m;

m = n/10;

n -= m*10;

sum += m*m*m + n*n*n;

if(sum==lotus)

return true;

else

return false;

}

}

【程式4】

題目:將一個正整數分解質因數。例如:輸入90,打印出90=2*3*3*5。

程式分析:對n進行分解質因數,應先找到一個最小的質數k,然後按下述步驟完成:

(1)如果這個質數恰等於n,則說明分解質因數的過程已經結束,打印出即可。

(2)如果n<>k,但n能被k整除,則應打印出k的值,並用n除以k的商,作為新的正整數n,重複執行第一步。

(3)如果n不能被k整除,則用k+1作為k的值,重複執行第一步。

public class Prog4{

public static void main(String[] args){

int n = 13;

decompose(n);

}

private static void decompose(int n){

System.out.print(n+"=");

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

while(n%i==0 && n!=i){

n/=i;

System.out.print(i+"*");

}

if(n==i){

System.out.println(i);

break;

}

}

}

}

【程式5】

題目:利用條件運算子的巢狀來完成此題:學習成績>=90分的同學用A表示,60-89分之間的用B表示,60分以下的用C表示。

程式分析:(a>b)?a:b這是條件運算子的基本例子。

public class Prog5{

public static void main(String[] args){

int n = -1;

try{

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

}catch(ArrayIndexOutOfBoundsException e){

System.out.println("請輸入成績");

return;

}

grade(n);

}

//成績等級計算

private static void grade(int n){

if(n>100 || n<0)

  System.out.println("輸入無效");

else{

  String str = (n>=90)?"分,屬於A":((n>60)?"分,屬於B":"分,屬於C");

  System.out.println(n+str);

}

}

}

【程式6】

題目:輸入兩個正整數m和n,求其最大公約數和最小公倍數。

程式分析:利用輾除法。

public class Prog6{

public static void main(String[] args){

int m,n;

try{

m = Integer.parseInt(args[0]);

n = Integer.parseInt(args[1]);

}catch(ArrayIndexOutOfBoundsException e){

System.out.println("輸入有誤");

return;

}

max_min(m,n);

}

//求最大公約數和最小公倍數

private static void max_min(int m, int n){

int temp = 1;

int yshu = 1;

int bshu = m*n;

if(n<m){

temp = n;

n = m;

m = temp;

}

while(m!=0){

temp = n%m;

n = m;

m = temp;

}

yshu = n;

bshu /= n;

System.out.println(m+"和"+n+"的最大公約數為"+yshu);

System.out.println(m+"和"+n+"的最小公倍數為"+bshu);

}

}

【程式7】

題目:輸入一行字元,分別統計出其中英文字母、空格、數字和其它字元的個數。

程式分析:利用while語句,條件為輸入的字元不為'\n'.

import java.util.Scanner;

public class Prog7_1{

public static void main(String[] args){

System.out.print("請輸入一串字元:");

Scanner scan = new Scanner(System.in);

String str = scan.nextLine();//將一行字元轉化為字串

scan.close();

count(str);

}

//統計輸入的字元數

private static void count(String str){

String E1 = "[\u4e00-\u9fa5]";//漢字

String E2 = "[a-zA-Z]";

String E3 = "[0-9]";

String E4 = "\\s";//空格

int countChinese = 0;

int countLetter = 0;

int countNumber = 0;

int countSpace = 0;

int countOther = 0;

char[] array_Char = str.toCharArray();//將字串轉化為字元陣列

String[] array_String = new String[array_Char.length];//漢字只能作為字串處理

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

  array_String[i] = String.valueOf(array_Char[i]);

//遍歷字串陣列中的元素

for(String s:array_String){

if(s.matches(E1))

  countChinese++;

else if(s.matches(E2))

  countLetter++;

else if(s.matches(E3))

  countNumber++;

else if(s.matches(E4))

  countSpace++;

else

  countOther++;

}

System.out.println("輸入的漢字個數:"+countChinese);

System.out.println("輸入的字母個數:"+countLetter);

System.out.println("輸入的數字個數:"+countNumber);

System.out.println("輸入的空格個數:"+countSpace);

System.out.println("輸入的其它字元個數:"+countSpace);

}

}

import java.util.*;

public class Prog7_2{

public static void main(String[] args){

  System.out.println("請輸入一行字元:");

  Scanner scan = new Scanner(System.in);

  String str = scan.nextLine();

  scan.close();

  count(str);

}

//統計輸入的字元

private static void count(String str){

List<String> list = new ArrayList<String>();

char[] array_Char = str.toCharArray();

for(char c:array_Char)

  list.add(String.valueOf(c));//將字元作為字串新增到list表中

Collections.sort(list);//排序

for(String s:list){

int begin = list.indexOf(s);

int end = list.lastIndexOf(s);

//索引結束統計字元數

if(list.get(end)==s)

  System.out.println("字元‘"+s+"’有"+(end-begin+1)+"個");

}

}

}

【程式8】

題目:求s=a+aa+aaa+aaaa+aa...a的值,其中a是一個數字。例如2+22+222+2222+22222(此時共有5個數相加),幾個數相加有鍵盤控制。

程式分析:關鍵是計算出每一項的值。

import java.util.Scanner;

public class Prog8{

public static void main(String[] args){

System.out.print("求s=a+aa+aaa+aaaa+...的值,請輸入a的值:");

Scanner scan = new Scanner(System.in).useDelimiter("\\s*");//以空格作為分隔符

int a = scan.nextInt();

int n = scan.nextInt();

scan.close();//關閉掃描器

System.out.println(expressed(2,5)+add(2,5));

}

//求和表示式

private static String expressed(int a,int n){

StringBuffer sb = new StringBuffer();

StringBuffer subSB = new StringBuffer();

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

  subSB = subSB.append(a);

  sb = sb.append(subSB);

  if(i<n)

    sb = sb.append("+");

}

sb.append("=");

return sb.toString();

}

//求和

private static long add(int a,int n){

long sum = 0;

long subSUM = 0;

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

subSUM = subSUM*10+a;

sum = sum+subSUM;

}

return sum;

}

}

【程式9】

題目:一個數如果恰好等於它的因子之和,這個數就稱為"完數"。例如6=1+2+3.程式設計找出1000以內的所有完數。

public class Prog9{

public static void main(String[] args){

int n = 10000;

compNumber(n);

}

//求完數

private static void compNumber(int n){

int count = 0;

System.out.println(n+"以內的完數:");

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

int sum = 0;

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

if((i%j)==0){

sum += j;

if(sum==i){

  System.out.print(i+" ");

  if((count++)%5==0)

    System.out.println();

    }

}

}

}

}

}

【程式10】

題目:一球從100米高度自由落下,每次落地後反跳回原高度的一半;再落下,求它在 第10次落地時,共經過多少米?第10次反彈多高?

import java.util.Scanner;

public class Prog10{

public static void main(String[] args){

System.out.print("請輸入小球落地時的高度和求解的次數:");

Scanner scan = new Scanner(System.in).useDelimiter("\\s");

int h = scan.nextInt();

int n = scan.nextInt();

scan.close();

distance(h,n);

}

//小球從h高度落下,經n次反彈後經過的距離和反彈的高度

private static void distance(int h,int n){

double length = 0;

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

length += h;

h /=2.0 ;

}

System.out.println("經過第"+n+"次反彈後,小球共經過"+length+"米,"+"第"+n+"次反彈高度為"+h+"米");

}

}

【程式11】

題目:有1、2、3、4個數字,能組成多少個互不相同且無重複數字的三位數?都是多少?

程式分析:可填在百位、十位、個位的數字都是1、2、3、4。組成所有的排列後再去 掉不滿足條件的排列。

public class Prog11{

public static void main(String[] args){

int count = 0;

int n = 0;

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

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

if(j==i)

  continue;

for(int k=1;k<5;k++){

if(k!=i && k!=j){

n = i*100+j*10+k;

  System.out.print(n+" ");

  if((++count)%5==0)

  System.out.println();

}

}

}

}

System.out.println();

System.out.println("符合條件的數共:"+count+"個");

}

}

【程式12】

題目:企業發放的獎金根據利潤提成。利潤(I)低於或等於10萬元時,獎金可提10%;利潤高於10萬元,低於20萬元時,低於10萬元的部分按10%提成,高於10萬元的部分,可可提成7.5%;20萬到40萬之間時,高於20萬元的部分,可提成5%;40萬到60萬之間時高於40萬元的部分,可提成3%;60萬到100萬之間時,高於60萬元的部分,可提成1.5%,高於100萬元時,超過100萬元的部分按1%提成,從鍵盤輸入當月利潤I,求應發放獎金總數?

程式分析:請利用數軸來分界,定位。注意定義時需把獎金定義成長整型。

import java.io.*;

public class Prog12{

public static void main(String[] args){

System.out.print("請輸入當前利潤:");

long profit = Long.parseLong(key_Input());

System.out.println("應發獎金:"+bonus(profit));

}

//接受從鍵盤輸入的內容

private static String key_Input(){

String str = null;

BufferedReader bufIn = new BufferedReader(new InputStreamReader(System.in));

try{

str = bufIn.readLine();

}catch(IOException e){

e.printStackTrace();

}finally{

try{

bufIn.close();

}catch(IOException e){

e.printStackTrace();

}

}

return str;

}

//計算獎金

private static long bonus(long profit){

long prize = 0;

long profit_sub = profit;

if(profit>1000000){

profit = profit_sub-1000000;

profit_sub = 1000000;

prize += profit*0.01;

}

if(profit>600000){

profit = profit_sub-600000;

profit_sub = 600000;

prize += profit*0.015;

}

if(profit>400000){

profit = profit_sub-400000;

profit_sub = 400000;

prize += profit*0.03;

}

if(profit>200000){

profit = profit_sub-200000;

profit_sub = 200000;

prize += prize*0.05;

}

if(profit>100000){

profit = profit_sub-100000;

profit_sub = 100000;

prize += profit*0.075;

}

prize += profit_sub*0.1;

return prize;

}

}

【程式13】

題目:一個整數,它加上100後是一個完全平方數,再加上168又是一個完全平方數,請問該數是多少?

程式分析:在10萬以內判斷,先將該數加上100後再開方,再將該數加上268後再開方,如果開方後的結果滿足如下條件,即是結果。

public class Prog13{

public static void main(String[] args){

int n=0;

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

if(isCompSqrt(i+100) && isCompSqrt(i+268)){

n = i;

break;

}

}

System.out.println("所求的數是:"+n);

}

//判斷完全平方數

private static boolean isCompSqrt(int n){

boolean isComp = false;

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

if(n==Math.pow(i,2)){

isComp = true;

break;

}

}

return isComp;

}

}

【程式14】

題目:輸入某年某月某日,判斷這一天是這一年的第幾天?

程式分析:以3月5日為例,應該先把前兩個月的加起來,然後再加上5天即本年的第幾天,特殊情況,閏年且輸入月份大於3時需考慮多加一天。

import java.util.Scanner;

public class Prog14{

public static void main(String[] args){

Scanner scan = new Scanner(System.in).useDelimiter("\\D");//匹配非數字

System.out.print("請輸入當前日期(年-月-日):");

int year = scan.nextInt();

int month = scan.nextInt();

int date = scan.nextInt();

scan.close();

System.out.println("今天是"+year+"年的第"+analysis(year,month,date)+"天");

}

//判斷天數

private static int analysis(int year, int month, int date){

int n = 0;

int[] month_date = new int[] {0,31,28,31,30,31,30,31,31,30,31,30};

if((year%400)==0 || ((year%4)==0)&&((year%100)!=0))

  month_date[2] = 29;

for(int i=0;i<month;i++)

  n += month_date[i];

return n+date;

}

}

【程式15】

題目:輸入三個整數x,y,z,請把這三個數由小到大輸出。

程式分析:我們想辦法把最小的數放到x上,先將x與y進行比較,如果x>y則將x與y的值進行交換,然後再用x與z進行比較,如果x>z則將x與z的值進行交換,這樣能使x最小。

import java.util.Scanner;

public class Prog15{

public static void main(String[] args){

Scanner scan = new Scanner(System.in).useDelimiter("\\D");

System.out.print("請輸入三個數:");

int x = scan.nextInt();

int y = scan.nextInt();

int z = scan.nextInt();

scan.close();

System.out.println("排序結果:"+sort(x,y,z));

}

//比較兩個數的大小

private static String sort(int x,int y,int z){

String s = null;

if(x>y){

int t = x;

x = y;

y = t;

}

if(x>z){

int t = x;

x = z;

z = t;

}

if(y>z){

int t = z;

z = y;

y = t;

}

s = x+" "+y+" "+z;

return s;

}

}

【程式16】

題目:輸出9*9口訣。

程式分析:分行與列考慮,共9行9列,i控制行,j控制列。

public class Prog16{

public static void main(String[] args){

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

for(int j=1;j<i+1;j++)

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

System.out.println();

}

}

}

【程式17】

題目:猴子吃桃問題:猴子第一天摘下若干個桃子,當即吃了一半,還不癮,又多吃了一個 第二天早上又將剩下的桃子吃掉一半,又多吃了一個。以後每天早上都吃了前一天剩下的一半零一個。到第10天早上想再吃時,見只剩下一個桃子了。求第一天共摘了多少。

程式分析:採取逆向思維的方法,從後往前推斷。

public class Prog17{

public static void main(String[] args){

int m = 1;

  for(int i=10;i>0;i--)

    m = 2*m + 2;

  System.out.println("小猴子共摘了"+m+"桃子");

}

}

【程式18】

題目:兩個乒乓球隊進行比賽,各出三人。甲隊為a,b,c三人,乙隊為x,y,z三人。已抽籤決定比賽名單。有人向隊員打聽比賽的名單。a說他不和x比,c說他不和x,z比,請程式設計序找出三隊賽手的名單。

import java.util.ArrayList;

public class Prog18{

String a,b,c;//甲隊成員

public static void main(String[] args){

String[] racer = {"x","y","z"};//乙隊成員

ArrayList<Prog18> arrayList = new ArrayList<Prog18>();

for(int i=0;i<3;i++)

  for(int j=0;j<3;j++)

    for(int k=0;k<3;k++){

     Prog18 prog18 = new Prog18(racer[i],racer[j],racer[k]);

     if(!prog18.a.equals(prog18.b) && !prog18.a.equals(prog18.c) && !prog18.b.equals(prog18.c) &&

        !prog18.a.equals("x") && !prog18.c.equals("x") && !prog18.c.equals("z"))

        arrayList.add(prog18);

    }

  for(Object obj:arrayList)

    System.out.println(obj);

}

//構造方法

private Prog18(String a,String b,String c){

this.a = a;

this.b = b ;

this.c = c;

}

public String toString(){

return "a的對手是"+a+"  "+"b的對手是"+b+"  "+"c的對手是"+c;

}

}

【程式19】

題目:打印出如下圖案(菱形)

    *

   ***

 ******

********

 ******

  ***

   *

程式分析:先把圖形分成兩部分來看待,前四行一個規律,後三行一個規律,利用雙重 for迴圈,第一層控制行,第二層控制列。

public class Prog19{

public static void main(String[] args){

int n = 5;

printStar(n);

}

//列印星星

private static void printStar(int n){

//列印上半部分

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

for(int j=0;j<2*n;j++){

   if(j<n-i)

     System.out.print(" ");

   if(j>=n-i && j<=n+i)

     System.out.print("*");

  }

  System.out.println();

}

//列印下半部分

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

System.out.print(" ");

for(int j=0;j<2*n-i;j++){

if(j<i)

     System.out.print(" ");

   if(j>=i && j<2*n-i-1)

     System.out.print("*");

}

System.out.println();

}

}

}

【程式20】

題目:有一分數序列:2/1,3/2,5/3,8/5,13/8,21/13...求出這個數列的前20項之和。

程式分析:請抓住分子與分母的變化規律。

public class Prog20{

public static void main(String[] args){

double n1 = 1;

double n2 = 1;

double fraction = n1/n2;

double Sn = 0;

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

  double t1 = n1;

  double t2 = n2;

  n1 = t1+t2;

  n2 = t1;

  fraction = n1/n2;

  Sn += fraction;

}

System.out.print(Sn);

}

}

【程式21】

題目:求1+2!+3!+...+20!的和

程式分析:此程式只是把累加變成了累乘。

public class Prog21{

public static void main(String[] args){

long sum = 0;

for(int i=0;i<20;i++)

  sum += factorial(i+1);

System.out.println(sum);

}

//階乘

private static long factorial(int n){

int mult = 1;

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

  mult *= i;

return mult;

}

}

【程式22】

題目:利用遞迴方法求5!。

程式分析:遞迴公式:fn=fn_1*4!

public class Prog22{

public static void main(String[] args){

System.out.println(fact(10));

}

//遞迴求階乘

private static long fact(int n){

if(n==1)

  return 1;

else

  return fact(n-1)*n;

}

}

【程式23】

題目:有5個人坐在一起,問第五個人多少歲?他說比第4個人大2歲。問第4個人歲數,他說比第3個人大2歲。問第三個人,又說比第2人大兩歲。問第2個人,說比第一個人大兩歲。最後問第一個人,他說是10歲。請問第五個人多大?

程式分析:利用遞迴的方法,遞迴分為回推和遞推兩個階段。要想知道第五個人歲數,需知道第四人的歲數,依次類推,推到第一人(10歲),再往回推。

public class Prog23{

public static void main(String[] args){

System.out.println(getAge(5,2));

}

//求第m位同志的年齡

private static int getAge(int m,int n){

if(m==1)

  return 10;

else

  return getAge(m-1,n)+n;

}

}

【程式24】

題目:給一個不多於5位的正整數,要求:一、求它是幾位數,二、逆序打印出各位數字。

public class Prog24{

public static void main(String[] args){

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

int i = 0;

int[] a = new int[5];

do{

a[i] = n%10;

  n /= 10;

  ++i;

}while(n!=0);

System.out.print("這是一個"+i+"位數,從個位起,各位數字依次為:");

for(int j=0;j<i;j++)

  System.out.print(a[j]+" ");

}

}

【程式25】

題目:一個5位數,判斷它是不是迴文數。即12321是迴文數,個位與萬位相同,十位與千位相同。

import java.io.*;

public class Prog25{

public static void main(String[] args){

int n = 0;

System.out.print("請輸入一個5位數:");

BufferedReader bufin = new BufferedReader(new InputStreamReader(System.in));

try{

  n = Integer.parseInt(bufin.readLine());

}catch(IOException e){

e.printStackTrace();

}finally{

try{

  bufin.close();

}catch(IOException e){

e.printStackTrace();

}

}

palin(n);

}

private static void palin(int n){

int m = n;

int[] a = new int[5];

if(n<10000 || n>99999){

System.out.println("輸入的不是5位數!");

return;

}else{

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

  a[i] = n%10;

  n /= 10;

  }

  if(a[0]==a[4] && a[1]==a[3])

    System.out.println(m+"是一個迴文數");

  else

    System.out.println(m+"不是迴文數");

    }

   }

}

【程式26】

題目:請輸入星期幾的第一個字母來判斷一下是星期幾,如果第一個字母一樣,則繼續 判斷第二個字母。

程式分析:用情況語句比較好,如果第一個字母一樣,則判斷用情況語句或if語句判斷第二個字母。

import java.io.*;

public class Prog26{

public static void main(String[] args){

String str = new String();

  BufferedReader bufIn = new BufferedReader(new InputStreamReader(System.in));

  System.out.print("請輸入星期的英文單詞前兩至四個字母):");

  try{

  str = bufIn.readLine();

  }catch(IOException e){

  e.printStackTrace();

  }finally{

  try{

  bufIn.close();

  }catch(IOException e){

  e.printStackTrace();

  }

  }

  week(str);

}

private static void week(String str){

int n = -1;

if(str.trim().equalsIgnoreCase("Mo") || str.trim().equalsIgnoreCase("Mon") || str.trim().equalsIgnoreCase("Mond"))

  n = 1;

if(str.trim().equalsIgnoreCase("Tu") || str.trim().equalsIgnoreCase("Tue") || str.trim().equalsIgnoreCase("Tues"))

  n = 2;

if(str.trim().equalsIgnoreCase("We") || str.trim().equalsIgnoreCase("Wed") || str.trim().equalsIgnoreCase("Wedn"))

  n = 3;

if(str.trim().equalsIgnoreCase("Th") || str.trim().equalsIgnoreCase("Thu") || str.trim().equalsIgnoreCase("Thur"))

  n = 4;

if(str.trim().equalsIgnoreCase("Fr") || str.trim().equalsIgnoreCase("Fri") || str.trim().equalsIgnoreCase("Frid"))

  n = 5;

if(str.trim().equalsIgnoreCase("Sa") || str.trim().equalsIgnoreCase("Sat") || str.trim().equalsIgnoreCase("Satu"))

  n = 2;

if(str.trim().equalsIgnoreCase("Su") || str.trim().equalsIgnoreCase("Sun") || str.trim().equalsIgnoreCase("Sund"))

  n = 0;

switch(n){

case 1:

  System.out.println("星期一");

  break;

case 2:

  System.out.println("星期二");

  break;

case 3:

  System.out.println("星期三");

  break;

case 4:

  System.out.println("星期四");

  break;

case 5:

  System.out.println("星期五");

  break;

case 6:

  System.out.println("星期六");

  break;

case 0:

  System.out.println("星期日");

  break;

default:

  System.out.println("輸入有誤!");

  break;

}

}

}

【程式27】

題目:求100之內的素數

public class Prog27{

public static void main(String[] args){

int n = 100;

System.out.print(n+"以內的素數:");

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

if(isPrime(i))

  System.out.print(i+" ");

}

}

//求素數

private static boolean isPrime(int n){

boolean flag = true;

for(int i=2;i<Math.sqrt(n)+1;i++)

if(n%i==0){

  flag = false;

  break;

}

return flag;

}

}

【程式28】

題目:對10個數進行排序

程式分析:可以利用選擇法,即從後9個比較過程中,選擇一個最小的與第一個元素交換, 下次類推,即用第二個元素與後8個進行比較,並進行交換。

public class Prog28{

public static void main(String[] args){

int[] a = new int[]{31,42,21,50,12,60,81,74,101,93};

for(int i=0;i<10;i++)

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

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

int temp = a[j];

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

a[j+1] = temp;

}

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

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

}

}

【程式29】

題目:求一個3*3矩陣對角線元素之和

程式分析:利用雙重for迴圈控制輸入二維陣列,再將a[i][i]累加後輸出。

public class Prog29{

public static void main(String[] args){

int[][] a = new int[][] {{100,2,3,},{4,5,6},{17,8,9}};

matrSum(a);

}

private static void matrSum(int[][] a){

int sum1 = 0;

int sum2 = 0;

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

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

   if(i==j) sum1 += a[i][j];

   if(j==a.length-i-1) sum2 += a[i][j];

  }

System.out.println("矩陣對角線之和分別是:"+sum1+"和"+sum2);

}

}

【程式30】

題目:有一個已經排好序的陣列。現輸入一個數,要求按原來的規律將它插入陣列中。

程式分析:首先判斷此數是否大於最後一個數,然後再考慮插入中間的數的情況,插入後此元素之後的數,依次後移一個位置。

import java.util.Scanner;

public class Prog30{

public static void main(String[] args){

int[] A = new int[]{0,8,7,5,9,1,2,4,3,12};

int[] B = sort(A);

print(B);

System.out.println();

        System.out.print("請輸入10個數的陣列:");

Scanner scan = new Scanner(System.in);

int a = scan.nextInt();

scan.close();

int[] C = insert(a,B);

print(C);

}

//選擇排序

private static int[] sort(int[] A){

int[] B = new int[A.length];

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

int min = A[i];

for(int j=i+1;j<A.length;j++){

if(min>A[j]){

int temp = min;

min = A[j];

A[j] = temp;

}

B[i] = min;

}

}

B[A.length-1] = A[A.length-1];

return B;

}

//列印

private static void print(int[] A){

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

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

}

//插入數字

private static int[] insert(int a,int[] A){

int[] B = new int[A.length+1];

for(int i=A.length-1;i>0;i--)

  if(a>A[i]){

   B[i+1] = a;

    for(int j=0;j<=i;j++)

      B[j] = A[j];

      for(int k=i+2;k<B.length;k++)

        B[k] = A[k-1];

      break;

  }

return B;

}

}

【程式31】

題目:將一個數組逆序輸出。

程式分析:用第一個與最後一個交換。

public class Prog31{

public static void main(String[] args){

int[] A = new int[]{1,2,3,4,5,6,7,8,9,};

print(A);

System.out.println();

int[] B = reverse(A);

print(B);

}

private static int[] reverse(int[] A){

for(int i=0;i<A.length/2;i++){

int temp = A[A.length-i-1];

A[A.length-i-1] = A[i];

A[i] = temp;

}

return A;

}

private static void print(int[] A){

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

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

}

}

【程式32】

題目:取一個整數a從右端開始的4~7位。

程式分析:可以這樣考慮:

(1)先使a右移4位。

(2)設定一個低4位全為1,其餘全為0的數。可用~(~0<<4)

(3)將上面二者進行&運算。

import java.util.Scanner;

public class Prog32{

public static void main(String[] msg){

//輸入一個長整數

Scanner scan = new Scanner(System.in);

long l = scan.nextLong();

scan.close();

//以下擷取字元

String str = Long.toString(l);

char[] ch = str.toCharArray();

int n = ch.length;

if(n<7)

  System.out.println("輸入的數小於7位!");

else

  System.out.println("擷取的4~7位數字:"+ch[n-7]+ch[n-6]+ch[n-5]+ch[n-4]);

}   

}

【程式33】

題目:打印出楊輝三角形(要求打印出10行如下圖)

程式分析:

        1

       1 1

     1 2 1

1 3 3 1

 1 4 6 4 1

1 5 10 10 5 1

public class Prog33{

public static void main(String[] args){

int[][] n = new int[10][21];

n[0][10] = 1;

for(int i=1;i<10;i++)

  for(int j=10-i;j<10+i+1;j++)

    n[i][j] = n[i-1][j-1]+n[i-1][j+1];

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

for(int j=0;j<21;j++){

if(n[i][j]==0)

  System.out.print("   ");

else{

    if(n[i][j]<10)

      System.out.print("  "+n[i][j]);//空格為了美觀需要

    else if(n[i][j]<100)

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

      else

        System.out.print(n[i][j]);

  }

}

System.out.println();

}

}

}

【程式34】

題目:輸入3個數a,b,c,按大小順序輸出。

程式分析:利用指標方法。

import java.util.Scanner;

public class Prog34{

public static void main(String[] args){

System.out.print("請輸入3個數:");

Scanner scan = new Scanner(System.in).useDelimiter("\\s");

int a = scan.nextInt();

int b = scan.nextInt();

int c = scan.nextInt();

scan.close();

if(a<b){

int t = a;

a = b;

b = t;

}

if(a<c){

int t = a;

a = c;

c = t;

}

if(b<c){

int t = b;

b = c;

c = t;

}

System.out.println(a+" "+b+" "+c);

}

}

【程式35】

題目:輸入陣列,最大的與第一個元素交換,最小的與最後一個元素交換,輸出陣列。

import java.util.Scanner;

public class Prog35{

public static void main(String[] args){

System.out.print("請輸入一組數:");

Scanner scan = new Scanner(System.in).useDelimiter("\\s");

int[] a = new int[50];

int m = 0;

while(scan.hasNextInt()){

a[m++] = scan.nextInt();

}

scan.close();

int[] b = new int[m];

for(int i=0;i<m;i++)

  b[i] = a[i];

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

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

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

int temp = b[j];

b[j] = b[j+1];

b[j+1] = temp;

}

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

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

}

}

【程式36】

題目:有n個整數,使其前面各數順序向後移m個位置,最後m個數變成最前面的m個數

import java.util.Scanner;

public class Prog36{

public static void main(String[] args){

final int N = 10;

System.out.print("請輸入10個數的陣列:");

Scanner scan = new Scanner(System.in);

int[] a = new int[N];

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

  a[i] = scan.nextInt();

System.out.print("請輸入一個小於10的數:");

int m = scan.nextInt();

scan.close();

int[] b = new int[m];

int[] c = new int[N-m];

for(int i=0;i<m;i++)

  b[i] = a[i];

for(int i=m,j=0;i<N;i++,j++)

  c[j] = a[i];

for(int i=0;i<N-m;i++)

  a[i] = c[i];

for(int i=N-m,j=0;i<N;i++,j++)

  a[i] = b[j];

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

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

}

}

【程式37】

題目:有n個人圍成一圈,順序排號。從第一個人開始報數(從1到3報數),凡報到3的人退出圈子,問最後留下的是原來第幾號的那位。

import java.util.Scanner;

public class Prog37{

public static void main(String[] args){

System.out.print("請輸入一個整數:");

Scanner scan = new Scanner(System.in);

int n = scan.nextInt();

scan.close();

//定義陣列變數標識某人是否還在圈內

boolean[] isIn = new boolean[n];

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

  isIn[i] = true;

//定義圈內人數、報數、索引

int inCount = n;

int countNum = 0;

int index = 0;

while(inCount>1){

if(isIn[index]){

countNum++;

if(countNum==3){

countNum = 0;

isIn[index] = false;

inCount--;

}

}

index++;

if(index==n)

  index = 0;

}

for(int i=0;i<n;i++)

  if(isIn[i])

    System.out.println("留下的是:"+(i+1));

}

}

【程式38】

題目:寫一個函式,求一個字串的長度,在main函式中輸入字串,並輸出其長度。

import java.util.Scanner;

public class Prog38{

public static void main(String[] args){

System.out.print("請輸入一串字元:");

Scanner scan = new Scanner(System.in).useDelimiter("\\n");

String strIn = scan.next();

scan.close();

char[] ch = strIn.toCharArray();

System.out.println(strIn+"共"+(ch.length-1)+"個字元");

}

}

【程式39】

題目:編寫一個函式,輸入n為偶數時,呼叫函式求1/2+1/4+...+1/n,當輸入n為奇數時,呼叫函式1/1+1/3+...+1/n(利用指標函式)

import java.util.Scanner;

public class Prog39{

public static void main(String[] args){

System.out.print("請輸入一個整數:");

Scanner scan = new Scanner(System.in);

int n = scan.nextInt();

scan.close();

if(n%2==0)

  System.out.println("結果:"+even(n));

else

  System.out.println("結果:"+odd(n));

}

//奇數

static double odd(int n){

double sum = 0;

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

sum += 1.0/i;

}

return sum;

}

//偶數

static double even(int n){

double sum = 0;

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

sum += 1.0/i;

}

return sum;

}

}

【程式40】

題目:字串排序。

public class Prog40{

public static void main(String[] args){

String[] str = {"abc","cad","m","fa","f"};

for(int i=str.length-1;i>=1;i--){

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

if(str[j].compareTo(str[j+1])<0){

String temp = str[j];

str[j] = str[j+1];

str[j+1] = temp;

}

}

}

for(String subStr:str)

  System.out.print(subStr+" ");

}

}

【程式41】

題目:海灘上有一堆桃子,五隻猴子來分。第一隻猴子把這堆桃子憑據分為五份,多了一個,這隻猴子把多的一個扔入海中,拿走了一份。第二隻猴子把剩下的桃子又平均分成五份,又多了一個,它同樣把多的一個扔入海中,拿走了一份,第三、第四、第五隻猴子都是這樣做的,問海灘上原來最少有多少個桃子?

public class Prog41{

public static void main(String[] args){

int n;

n = fun(0);

System.out.println("原來有"+n+"個桃子");

}

private static int fun(int i){

if(i==5)

  return 1;

else

  return fun(i+1)*5+1;

}

}

【程式42】

題目:809*??=800*??+9*??+1

其中??代表的兩位數,8*??的結果為兩位數,9*??的結果為3位數。求??代表的兩位數,及809*??後的結果。

public class Prog42{

public static void main(String[] args){

int n = 0;

boolean flag = false;

for(int i=10;i<100;i++)

  if(809*i==800*i+9*i+1){

   flag = true;

   n = i;

   break;

  }

if(flag)

  System.out.println(n);

else

  System.out.println("無符合要求的數!");

}

}

【程式43】

題目:求0—7所能組成的奇數個數。

public class Prog43{

public static void main(String[] args){

int count = 0;

//宣告由數字組成的數

int n = 8;

//一位數

count = n/2;

//兩位數

count += (n-1)*n/2;

//三位數

count += (n-1)*n*n/2;

//四位數

count += (n-1)*n*n*n/2;

//五位數

count += (n-1)*n*n*n*n/2;

//六位數

count += (n-1)*n*n*n*n*n/2;

//七位數

count += (n-1)*n*n*n*n*n*n/2;

System.out.println("0-7所能組成的奇數個數:"+count);

}

}

【程式44】

題目:一個偶數總能表示為兩個素數之和。

import java.util.Scanner;

public class Prog44{

public static void main(String[] args){

System.out.print("請輸入一個偶數:");

Scanner scan = new Scanner(System.in);

int n = scan.nextInt();

scan.close();

if(n%2!=0){

  System.out.println("您輸入的不是偶數!");

  return;

}

twoAdd(n);

}

//偶數分解為素數之和

private static void twoAdd(int n){

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

if(isPrime(i)&&isPrime(n-i)){

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

break;

}

}

}

//判斷素數

private static boolean isPrime(int m){

boolean flag = true;

for(int i=2;i<Math.sqrt(m)+1;i++){

if(m%i==0){

flag = false;

break;

}

}

return flag;

}

}

【程式45】

題目:判斷一個素數能被幾個9整除

import java.util.Scanner;

public class Prog45{

public static void main(String[] args){

System.out.print("請輸入一個數:");

  Scanner scan = new Scanner(System.in);

  long l = scan.nextLong();

  long n = l;

  scan.close();

  int count = 0;

  while(n>8){

  n /= 9;

  count++;

  }

  System.out.println(l+"能被"+count+"個9整除。");

}

}

【程式46】

題目:兩個字串連線程式

public class Prog46{

public static void main(String[] args){

String str1 = "lao lee";

  String str2 = "牛刀";

  String str = str1+str2;

  System.out.println(str);

}

}

【程式47】

題目:讀取7個數(1—50)的整數值,每讀取一個值,程式打印出該值個數的*。

import java.util.Scanner;

public class Prog47{

public static void main(String[] args){

System.out.print("請輸入7個整數(1-50):");

Scanner scan = new Scanner(System.in);

int n1 = scan.nextInt();

int n2 = scan.nextInt();

int n3 = scan.nextInt();

int n4 = scan.nextInt();

int n5 = scan.nextInt();

int n6 = scan.nextInt();

int n7 = scan.nextInt();

scan.close();

printStar(n1);

printStar(n2);

printStar(n3);

printStar(n4);

printStar(n5);

printStar(n6);

printStar(n7);

}

static void printStar(int m){

System.out.println(m);

for(int i=0;i<m;i++)

  System.out.print("*");

System.out.println();

}

}

【程式48】

題目:某個公司採用公用電話傳遞資料,資料是四位的整數,在傳遞過程中是加密的,加密規則如下:每位數字都加上5,然後用和除以10的餘數代替該數字,再將第一位和第四位交換,第二位和第三位交換。

public class Prog48{

public static void main(String[] args){

int n = 1234;

int[] a = new int[4];

for(int i=3;i>=0;i--){

  a[i] = n%10;

  n /= 10;

}

for(int i=0;i<4;i++)

  System.out.print(a[i]);

System.out.println();

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

  a[i] += 5;

  a[i] %= 10;

}

int temp1 = a[0];

a[0] = a[3];

a[3] = temp1;

int temp2 = a[1];

a[1] = a[2];

a[2] = temp2;

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

  System.out.print(a[i]);

}

}

【程式49】

題目:計算字串中子串出現的次數

public class Prog49{

public static void main(String[] args){

String str = "I come from County DingYuan Province AnHui.";

char[] ch = str.toCharArray();

int count = 0;

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

if(ch[i]==' ')

  count++;

}

count++;

System.out.println("共有"+count+"個字串");

}

}

【程式50】

題目:有五個學生,每個學生有3門課的成績,從鍵盤輸入以上資料(包括學生號,姓名,三門課成績),計算出平均成績,將原有的資料和計算出的平均分數存放在磁碟檔案"stud"中。

import java.io.*;

public class Prog50{

//定義學生模型

String[] number = new String[5];

String[] name = new String[5];

float[][] grade = new float[5][3];

float[] sum = new float[5];

public static void main(String[] args) throws Exception{

Prog50 stud = new Prog50();

stud.input();

stud.output();

}

//輸入學號、姓名、成績

void input() throws IOException{

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

//錄入狀態標識

boolean isRecord = true;

while(isRecord){

try{

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

  System.out.print("請輸入學號:");

  number[i] = br.readLine();

  System.out.print("請輸入姓名:");

  name[i] = br.readLine();

  for(int j=0;j<3;j++){

  System.out.print("請輸入第"+(j+1)+"門課成績:");

  grade[i][j] = Integer.parseInt(br.readLine());

  }

  System.out.println();

  sum[i] = grade[i][0]+grade[i][1]+grade[i][2];

  }

    isRecord = false;

    }catch(NumberFormatException e){

     System.out.println("請輸入一個數字!");

  }

}

}

//輸出檔案

void output() throws IOException{

FileWriter fw = new FileWriter("E://java50//stud.txt");

BufferedWriter bw = new BufferedWriter(fw);

bw.write("No.  "+"Name  "+"grade1  "+"grade2  "+"grade3  "+"average");

bw.newLine();

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

  bw.write(number[i]);

  bw.write("  "+name[i]);

  for(int j=0;j<3;j++)

    bw.write("  "+grade[i][j]);

  bw.write("  "+(sum[i]/5));

  bw.newLine();

}

bw.close();

}

}