[編程題] Java基礎編程練習題(一)

點擊上方“Coder編程”,選擇“置頂公衆號”

技術文章第一時間送達!

Java基礎編程練習題(一)

1.編寫一個Java程序,用if-else語句判斷某年份是否爲閏年。(分支)

// Programme Name LeapYear.java
public class LeapYear{
public static void main(String args[]){
int year=2010; 
if(args.length!=0)
  year=Integer.parseInt(args[0]);
if((year%4==0 && year%100!=0)||(year%400==0))
 System.out.println(year+" 年是閏年。");
else
 System.out.println(year+" 年不是閏年。");
   }
 }//if-else語句

2.編寫一個Java程序在屏幕上輸出1!+2!+3!+……+10!的和。(循環)

// programme name ForTest.java
public class ForTest { 
public static void main( String args[] ) {
  int  i,j,mul,sum=0;
for(i=1;i<=10;i++) {
mul=1;
for(j=1,j<=i;j++) {
mul=mul*j;
}
      sum=sum+mul;
}
System.out.println(“1!+2!+3!+……+10!= ”+sum);
}
}

3.依次輸入10個學生成績,判斷學生(優秀、良好、中等、及格、不及格)並計算人數

提示:switch

4.使用冒泡排序(數組)

public class BubbleSort {

    public static void main(String[] args) {
        int[] array={63,4,24,1,3,5};
        BubbleSort sorter=new BubbleSort();
        sorter.sort(array);
    }
    //冒泡排序
    public void sort(int[] array){
        for(int i=1;i<array.length;i++)
            for(int j=0;j<array.length-1;j++){
                if(array[j]>array[j+1]){
                    int temp=array[j];
                    array[j]=array[j+1];
                    array[j+1]=temp;
                }
            }
           showArray(array);  
    }
    //遍歷數組,並輸出數組的元素。
    public void showArray(int[] array){
        for(int i=0;i<array.length;i++){      
            System.out.print(array[i]+"\t");
        }
        System.out.println();
    }
}

5.實現會員註冊,要求用戶名長度不小於3,密碼長度不小於6,註冊時兩次輸入密碼必須相同 (字符串)

import java.util.Scanner;
public class Register {
    String name;
    String password;
    String newPassword;
    ///////////
    public void nameExe(){
        Scanner input=new Scanner(System.in);
        System.out.println("請輸入用戶名,密碼和驗證密碼");
         System.out.print("用戶名:");
         name=input.next();
         System.out.print("密碼:");
         password=input.next();
         System.out.print("驗證密碼:");
         newPassword=input.next();

        while(name.length()<3||(password.equals(newPassword)==false)
                ||(password.length()<6)){
            if(name.length()<3){
            System.out.println("用戶名不能小於3");
            }
            if((password.equals(newPassword)==false)||password.length()<6){
            System.out.println("兩次輸入密碼不一樣或密碼不能小於6位");   
            }
            System.out.println("\n"+"請重新輸入");
             System.out.print("用戶名:");
             name=input.next();
             System.out.print("密碼:");
             password=input.next();
             System.out.print("驗證密碼:");
             newPassword=input.next(); 
        }
         System.out.println("註冊成功!");
        }   
        }

 public class Verify {
    public static void main(String[] args) {
        Register m1=new Register();
        m1.nameExe();
    }
}

6.一個景區根據遊人的年齡收取不同價格的門票。請編寫遊人類,根據年齡段決定能夠購買的門票價格並輸出,然後寫出測試類測試該類(類的基本實現)

public class Tourist {
    int age;
    int ticketPrice;

    public void setAge(int age){
        this.age=age;   
    }

     public void ticket(){
         if(age>0&&age<12)
             ticketPrice=20;
         else if(age<20)
             ticketPrice=40;
         else if(age<50)
             ticketPrice=80;
         else  
             ticketPrice=35;
         System.out.println("門票價格:"+ticketPrice); 
     }
}/////

import java.util.Scanner;
public class Test {
    public static void main(String[] args) {
        Scanner input=new Scanner(System.in);
        Tourist t1=new Tourist();
        System.out.print("請輸入年齡:");
        t1.setAge(input.nextInt());
        t1.ticket();

    }

}

7.按要求實現以下類

(1)編寫一個圓類Circle
該類擁有:
①一個成員變量
Radius(私有,浮點型); // 存放圓的半徑;
②兩個構造方法
         Circle( )                 // 將半徑設爲0
         Circle(double  r )         //創建Circle對象時將半徑初始化爲r
③ 三個成員方法
           double getArea( )       //獲取圓的面積
           double getPerimeter( )   //獲取圓的周長
           void  show( )          //將圓的半徑、周長、面積輸出到屏幕
(2)編寫一個圓柱體類Cylinder,它繼承於上面的Circle類。還擁有:
①一個成員變量
double hight(私有,浮點型); // 圓柱體的高;
②構造方法
         Cylinder (double r, double  h )           //創建Circle對象時將半徑初始化爲r
③ 成員方法
           double getVolume( )             //獲取圓柱體的體積
           void  showVolume( )             //將圓柱體的體積輸出到屏幕
編寫應用程序,創建類的對象,分別設置圓的半徑、圓柱體的高,計算並分別顯示圓半徑、圓面積、圓周長,圓柱體的體積。

//Programme Name TestCylinder.java
 class Circle {                      //定義父類--園類
    private double radius;          //成員變量--園半徑
    Circle() {                      //構造方法
        radius=0.0;
    }
    Circle(double r) {              //構造方法 
        radius=r; 
    }
    double getPerimeter() {         //成員方法--求園周長
        return 2*Math.PI*radius;
    }
    double getArea() {              //成員方法--求園面積
        return Math.PI*radius*radius;
    }
    void disp() {                   //成員方法--顯示園半徑、周長、面積
        System.out.println("圓半徑="+radius);
        System.out.println("圓周長="+getPerimeter());
        System.out.println("圓面積="+getArea());   
    }
}

class Cylinder extends Circle {     //定義子類--圓柱類
    private double hight;           //成員變量--園柱高
    Cylinder(double r,double h) {   //構造方法 
        super(r);
        hight=h;
    }
    public double getVol() {        //成員方法--求園柱體積
        return getArea()*hight;
    }
    public void dispVol() {         //成員方法--顯示園柱體積
        System.out.println("圓柱體積="+getVol());
    }
}
public class TestCylinder {         //定義主類
public static void main(String[] args) {    //主程入口
    Circle Ci=new Circle(10.0); // 生成園類實例
    Ci.disp(); // 調用園類的方法
        Cylinder Cyl=new Cylinder(5.0,10.0);    //生成圓柱類實例
        Cyl.disp();                             //調用父類方法
        Cyl.dispVol();                          //調用子類方法
    }
}

8.編寫一個Java應用程序,從鍵盤讀取用戶輸入兩個字符串,並重載3個函數分別實現這兩個字符串的拼接、整數相加和浮點數相加。要進行異常處理,對輸入的不符合要求的字符串提示給用戶,不能使程序崩潰。(異常處理)

//programme name Strinput.java
import java.io.*;
public class Strinput 
{
  public static void main(String args[]) {
       String s1=null,s2=null,ss,si,sf;
       int i1,i2;
       float f1,f2;
       BufferedReader strin=new  BufferedReader(new InputStreamReader(System.in));
       try{System.out.print ("輸入第一個字符串:" );
           s1= strin.readLine();
           System.out.print ("輸入第二個字符串:" );
           s2= strin.readLine();}
       catch(Exception e){ System.out.println(e.getMessage());}
       i1 = Integer.parseInt(s1);
       i2 = Integer.parseInt(s2);
       f1 = Float.parseFloat(s1);
       f2 = Float.parseFloat(s2);
       ss = strAdd(s1,s2);
       si = strAdd(i1,i2);
       sf = strAdd(f1,f2);
       System.out.println ("輸入的二個字符串相加結果爲:"+ss );
       System.out.println ("輸入字符串轉換爲整數相加結果爲:"+si );
       System.out.println ("輸入字符串轉換爲浮點數相加結果爲:"+sf );
    }
   static  String strAdd(String str1,String str2) {
return str1+str2;
}
static  String strAdd(int int1,int int2) {
return  String.valueOf(int1+int2);
}
static  String strAdd(float flt1,float flt2) {
return  String.valueOf (flt1+flt2);
}
 }

9.應用FileInputStream類,編寫應用程序,從磁盤上讀取一個Java程序,並將源程序代碼顯示在屏幕上。

(被讀取的文件路徑爲:E:/myjava/Hello.java)

// Programme Name FISDemo.java
import java.io.*;
  public class FISDemo {
  public static void main(String args[]) {
    byte[] buf=new byte[2056];
    try{
     FileInputStream fileIn=new FileInputStream("e:/myjava/Hello.java");
     int bytes=fileIn.read(buf,0,2056);
     String str=new String(buf,0,bytes);
     System.out.println(str);
}catch(Exception e){
 e.printStackTrace( );
}
}

10. 編寫一個Java程序將當100,101,102,103,104,105個數以數組的形式寫入到Dest.txt文件中,並以相反的順序讀出顯示在屏幕上。(文件)

import java.io.*;
  public class IODemo {
    public static void main( String args[] ) {
          int data[] = {100,101,102,103,104,105};
          int[] t=new int[200];
          try{ 
             // File file=new File("dest.txt");
              DataOutputStream out = new  DataOutputStream (new  FileOutputStream("dest.txt"));
          for(int i=0;i<data.length;i++) 
              out.writeInt(data[i]);
          out.close();
          DataInputStream in = new  DataInputStream (new  FileInputStream("dest.txt"));
          //先讀出來再倒序輸出
          for(int i=0;i<data.length;i++) {
              t[i]=in.readInt();
              }
          for(int i= data.length-1;i>= 0;i--) {
              System.out.print("  "+t[i]);
              }

         /* for(int i= data.length-1;i>= 0;i--) {
              t=in.readInt(data[i]);
              System.out.print("  "+t);
              }*/
          System.out.println( );
          in.close();
          }catch(IOException e)
          {
              System.out.println(e.getMessage());}
          }
      }

推薦

400道——大廠Java選擇題

HR面試都會問什麼問題?(上)

HR面試都會問什麼問題(下)

文末

歡迎關注個人微信公衆號:Coder編程
歡迎關注Coder編程公衆號,主要分享數據結構與算法、Java相關知識體系、框架知識及原理、Spring全家桶、微服務項目實戰、DevOps實踐之路、每日一篇互聯網大廠面試或筆試題以及PMP項目管理知識等。更多精彩內容正在路上~
新建了一個qq羣:315211365,歡迎大家進羣交流一起學習。謝謝了!也可以介紹給身邊有需要的朋友。

文章收錄至
Github: https://github.com/CoderMerlin/coder-programming
Gitee: https://gitee.com/573059382/coder-programming
歡迎關注並star~

微信公衆號

                   我知道你 “在看

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章