Java基礎面試題總結-編程題總結

 

 1.理髮題(10份)express

1110元,洗剪吹31元,能夠多少次洗剪吹?最後還剩多少?數組

2)一次剪頭髮15元和一次洗頭20元,平均每次消費多少錢?app

public class Test04 {
    public static void main(String[]args){
        double money=110;
        double costone=31;
        int count=(int)(money/costone);
        System.out.println("能夠理髮"+count+"");
        double lastmoney=money%costone;
        System.out.println("剩餘"+lastmoney+"");
        double avgmoney=(15d+20d)/2d;
        System.out.println("理髮15,洗頭20,那麼平均消費是:"+avgmoney);函數

2.打印九九乘法表(15分)測試

public class NineNine {
    public static void main(String[] args) {
        for (int i= 1; i <=9 ; i++) {
          for (int j =1; j <=i ; j++) {
              System.out.print(j+"*"+i+"="+i*j+"\t");
            }
            System.out.println();
        }
    }
}this

3.編寫萬用表程序url

1 電壓擋spa

2 電流擋.net

3 電阻檔blog

4 其餘檔位

5 退出

注意:使用scannersystem.in)時,使用完畢後,必定要關閉掃描器,由於system.in屬於IO流,一旦打開,它一直在佔用資源,所以使用完畢後切記要關閉。(15分)

public class MulTimter {
    public static void main(String[] args) {
        System.out.println("歡迎使用萬用表:");
        Scanner scanner = new Scanner(System.in);
        System.out.println("請選擇檔位:1電壓檔  2電流檔3電阻檔  4其餘檔位  5退出  ");
        System.out.println("請輸入你的選擇:");
        String input = scanner.next();
// 過濾無效的選擇
        while (!input.equals("1") && !input.equals("2")&& !input.equals("3")
                && !input.equals("4") && !input.equals("5")) {
            System.out.println("請輸入有效的選擇:");
            input = scanner.next();// 獲取用戶輸入的選擇
        }
        // 判斷選擇
        switch (input) {
            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;
        }
        scanner.close();
    }
}

4.編寫三個方法,分別得出一個數組的最大值,最小值,平均值。(15分)

  public class array {
    public static void main(String[] args) {
        int[]array={1,2,3,4,5,6};
        int max=numMax(array);
        System.out.println("最大的數是:" + max);
        int min=numMin(array);
        System.out.println("最小的數是:" + min);
        double avg =numAvg(array);
        System.out.println("平均數是:" +avg);
    }

    private static double numAvg(int[] array) {
        double sum=0;
        double numAvg=0;
        for (int i = 0; i <array.length ; i++) {
           sum+=array[i];
        }
        numAvg=sum/array.length;
        return numAvg;
    }

    private static int numMin(int[] array) {
        int numMin=array[0]; //定義一個最小值
        for (int i = 0; i <array.length ; i++) {
           if (numMin>array[i]){
               numMin=array[i];
           }
        }
        return numMin;
    }

    private static int numMax(int[] array) {
        int numMax=0;
        for (int i = 0; i <array.length ; i++) {
            if (numMax<array[i]){
                numMax=array[i];
            }
        }
        return numMax;
    }
}

5.建立寵物類(屬性:名字 ,體重 方法: 奔跑,捕食)在DEMO類實例化寵物,設置名字,調用奔跑,捕食方法(15分)

public class Pet {
    private String name;
    private double weight;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getWeight() {
        return weight;
    }

    public void setWeight(double weight) {
        this.weight = weight;
    }

    void run(){
        System.out.println("它在奔跑");
    }
    void catchFood(){
        System.out.println("它在捕食");
    }
}
class demo{
    public static void main(String[] args) {
        Pet pet = new Pet();
        pet.setName("麒麟");
        pet.setWeight(100);
        System.out.println("個人寵物:" + pet.getName()+",體重:" + pet.getWeight()+"kg");
        pet.run();
        pet.catchFood();
    }
}

6.接收用戶輸入的5門功課而且,計算平均分。(15分)

給用戶評級60-80良,81-90好,91-100優秀。

public class Test05 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        double array[]=new double[5];
        System.out.println("請輸入5門功課的成績");
        double sum = 0;// 定義分數總和值
        double avg = 0;// 定義平均分值
        for (int i = 0; i <5; i++) {
        System.out.print("請輸入" + (i + 1)+ "第門成績:");
           array[i] = scanner.nextDouble();
           sum+=array[i];
        }
        avg = sum / array.length;// 求得平均分值
        String rank = avg >=91 ? "優秀" : (avg >=81 ? "" : (avg >=60) ? ""
                : "");
        System.out.println("五門科目的平均分是:" + avg+"\t評級爲:" + rank);
        scanner.close();
    }
}

7.建立一個面積類,能夠計算長方形,圓形的面積。並在DEMO類測試,計算長方形面積,圓的面積。(15分)

public class Circele{
    private double radius = 0;// 圓的半徑
    public Circele(double radius){// 經過構造方法,得到半徑
        this.radius = radius;
    }
    //得到圓形面積
    double getArea() {
        return Math.PI * radius * radius;
    }
}

public class Rectangle {
    private double height=0;
    private double weigtht=0;
    public Rectangle(double height,double weigtht){
      this.height=height;
      this.weigtht=weigtht;
    }
    double getarea(){
        return height*weigtht;
    }
}

public class Demo {
    public static void main(String[] args) {
        Circele circele = new Circele(10);
        System.out.println("圓的面積是:"+circele.getArea());
        Rectangle rectangle = new Rectangle(10, 4);
        System.out.println("長方形面積是:"+rectangle.getarea());
    }
}

8.判斷200-300之間有多少個素數,並輸出全部素數。

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

 

public class suShu {
    public static void main(String[] args) {
        int sum = 0;
        for (int i = 200; i<= 300; i++)
        {
            boolean isFind = false;
            for (int j= 2; j <i; j++)
            {
                if (i%j==0)
                {
                    isFind = true;
                    break;
                }
             }
            if (!isFind)
            {
                System.out.println(i);
                sum += i;
            }
        }
        System.out.println("200300之間的質數之和是:"+sum);
    }
}

9.輸入一行字符,分別統計出其中英文字母、空格、數字和其它字符的個數。

 程序分析:利用while語句,條件爲輸入的字符不爲'\n'.

 public class CountAll {
    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);

    }
}

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

public class Sum {
    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;

    }
}

11.輸入某年某月某日,判斷這一天是這一年的第幾天?

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

public class WhichDay {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in).useDelimiter("\\D");//匹配非數字
        System.out.println("請輸入當前日期(年--日:");
        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;

    }
}

12.輸入三個整數x,y,z,請把這三個數由小到大輸出

程序分析:咱們想辦法把最小的數放到x上,先將xy進行比較,若是x>y則將xy的值進行交換,而後再用xz進行比較,若是x>z則將xz的值進行交換,這樣能使x最小

public class Compare {
    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;

    }
    }

13.求1+2!+3!+...+20!的和

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

public class ForTest {
    public static void main(String[] args){
    int x=1;
    int sum=0;
     for (int i = 1; i <=20 ; i++) {
        x=x*i;
        sum+=x;
        }
        System.out.println(sum);
    }
}

14.利用遞歸方法求5!

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

public class Fn {
    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;
     }
    }
}

15.請輸入星期幾的第一個字母來判斷一下是星期幾,若是第一個字母同樣,則繼續 判斷第二個字母。

程序分析:用狀況語句比較好,若是第一個字母同樣,則判斷用狀況語句或if語句判斷第二個字母。

public class Week {
    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;

        }

    }
}

16.100以內的素數

程序分析:素數是不能被1或者它自己以外的其餘數整除的整數

public class Sushu {
    public static void main(String[] args) {
        int i,j;
        for ( i = 1; i <=100;i++) {
            for ( j =2; j <i ; j++) {
              if ((i%j)==0){
                  break;
              }
            }
            if (i==j){
                System.out.println(i);
            }
        }
    }
}

17.輸入3個數a,b,c,按大小順序輸出。

public class ThreeNumber {
    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);
    }
}

18.寫一個函數,求一個字符串的長度,在main函數中輸入字符串,並輸出其長度。

//注意:next()方法讀取到空白符就結束了,nextLine()讀取到回車結束也就是「\r」
public class StringLenth {
    public static void main(String[] args) {
        System.out.print("請輸入一行字符串:");
        Scanner scanner = new Scanner(System.in).useDelimiter("\\n");
        String str = scanner.nextLine();
        scanner.close();
        //將字符串轉化爲字符數組
        char[]chars=str.toCharArray();
        System.out.println(str+""+(chars.length-1)+"個字符");

    }
}

19.對字符串的排序

public class letter {
    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+" ");

    }
}

20.兩個字符串鏈接程序

public class Connection {
    public static void main(String[] args) {
        String str1="你好,";
        String str2="世界歡迎你!";
        String str=str1+str2;
        System.out.println(str);
    }
}

21.統計字符串中子串出現的次數

public class Character {
    public static void main(String[] args){
        String str = "I come from China";
        char[] ch = str.toCharArray();
        int count = 0;
        for(int i=0;i<ch.length;i++){
            if(ch[i]==' ')
                count++;
        }
        count++;
        System.out.println("共有"+count+"個字串");
    }
}

22.有五個學生,每一個學生有3門課的成績,從鍵盤輸入以上數據(包括學生號,姓名,三門課成績),計算出平均成績,將原有的數據和計算出的平均分數存放在磁盤文件"stud"中。

public class Student {
     //定義學生數組模型
    String[] number = new String[5];
    String[] name = new String[5];
    float[][] grade = new float[5][3];
    float[] sum = new float[5];

    /**
     * 輸入學號、姓名、成績
     */
    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 (Exception e){
                System.out.print("請輸入數字!");
            }
        }
    }

     /**
     * 輸出文件內容
     * @param
     */
    void output() throws IOException {
        FileWriter fw = new FileWriter("E:\\Me\\個人下載\\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]);
            for (int j = 0; j <3 ; j++) {
                bw.write(" "+grade[i][j]);
                bw.write(" "+sum[j]/5);
                bw.newLine();
            }
        }
        bw.close();
    }

    public static void main(String[] args) throws IOException {
        Student student = new Student();
        student.input();
        student.output();
    }
}

23.從硬盤中複製一個文件內容到另外一個文件中

public class FileCopy {
    public static void main(String[] args) {
      copyAToB();
    }
    public static void copyAToB(){
        File file=new File("E:/Me/個人下載/stud.txt");
        File file2=new File("E:/Me/個人下載/b.txt");
        if(!file2.exists()){
            try {
                file2.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        InputStream in=null;
        OutputStream out=null;
        try {
            in=new FileInputStream(file);//創建到a的流
            out=new FileOutputStream(file2);//創建到b的流
            int i;
            while((i=in.read())!=-1){//a讀取字母
                out.write(i);//將字母寫到b
            }
            System.out.println("複製成功!");

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                out.close();
                in.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    }
}

 

 參考資料:https://blog.csdn.net/wenzhi20102321/article/details/52430616

https://blog.csdn.net/cao2219600/article/details/80973336

相關文章
相關標籤/搜索