• JavaSE基础面试题(二)


    1、用循环控制语句打印输出:1+3+5+...+99=?的结果

    答案一:
        public static void main(String[] args) {
            int sum = 0;
            for (int i = 1; i <= 99; i+=2) {
                sum += i;
            }
            System.out.println("sum = " + sum);
        }
    答案二:
        public static void main(String[] args) {
            int sum = 0;
            for (int i = 1; i < 100; i++) {
                if (i % 2 != 0) {
                    sum += i;
                }
            }
            System.out.println("sum = " + sum);
        }

    2、请写一个冒泡排序,实现{5,7,3,9,2}从小到大排序

    答案一:
            int[] arr = { 5, 7, 3, 9, 2 };
            for (int i = 1; i < arr.length; i++) {
                for (int j = 0; j < arr.length - i; j++) {
                    if (arr[j] > arr[j + 1]) {
                        int temp = arr[j];
                        arr[j] = arr[j + 1];
                        arr[j + 1] = temp;
                    }
                }
            }
    答案二:
            int[] arr = { 5, 7, 3, 9, 2 };
            for (int i = 1; i < arr.length; i++) {
                for (int j = arr.length-1; j >= i; j--) {
                    if (arr[j] < arr[j - 1]) {
                        int temp = arr[j];
                        arr[j] = arr[j - 1];
                        arr[j - 1] = temp;
                    }
                }
            }

    3、编写方法实现:求某年某月某日是这一年的第几天

    提示:闰年(1)能被4整除不能被100整除(2)能被400整除

    public static int daysOfYear(int year, int month, int day){
            int[] daysOfMonth = {31,28,31,30,31,30,31,31,30,31,30,31};
                                   补充代码                        
        }
    答案一:
        public static int daysOfYear(int year, int month, int day){
            int[] daysOfMonth = {31,28,31,30,31,30,31,31,30,31,30,31};
            int sum = day;
            for(int i=0;i< month-1; i++){
                sum += daysOfMonth[i];
            }
            if(month>2){
                if(year%4==0 && year%100!=0 || year%400==0){
                    sum++;
                }
            }
            return sum;
        }
    答案二:
        public static int daysOfYear(int year, int month, int day){
            int[] daysOfMonth = {31,28,31,30,31,30,31,31,30,31,30,31};
            int sum = day;
            for(int i=0;i< month-1; i++){
                sum += daysOfMonth[i];
                if(i==1){
                    if(year%4==0 && year%100!=0 || year%400==0){
                        sum++;
                    }
                }
            }
            return sum;
        }

    4、通项公式如下:f(n)=n + (n-1) + (n-2) + .... + 1,其中n是大于等于5并且小于10000的整数,例如:f(5) = 5 + 4 + 3 + 2 + 1f(10) = 10 + 9 + 8 + 7+ 6 + 5 + 4 + 3 + 2 + 1,请用非递归的方式完成方法long f( int n)的方法体。

    答案一:非递归
        public static long f(int n) {
            long sum = 0;
            for (int i = 1; i <= n; i++) {
                sum += i;
            }
            return sum;
        }

    5、1+2+3+...+20!的和

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

    6、输出一个如下图形,一共有n行,第n行有2n-1*,完成方法public void printStar(int n)的方法体

        *
       ***
      *****
     *******
    *********
    public void printStar(int n) {
            for (int i = 1; i <= n; i++) {
                for (int j = 0; j < n - i; j++) {
                    System.out.print(" ");
                }
                for (int j = 0; j < 2 * i - 1; j++) {
                    System.out.print("*");
                }
                System.out.println();
            }
        }

    7、请编写代码把一个字符串反转,例如:hello1234,反转后:4321olleh

    答案一:
    public class Test {
        public static void main(String[] args) {
            String str = "hello1234";
            StringBuilder s = new StringBuilder(str);
            s.reverse();
            str = s.toString();
            System.out.println(str);
        }
    }
    答案二:
    public class Test {
        public static void main(String[] args) {
            String str = "hello1234";
            char[] array = str.toCharArray();
            for (int i = 0; i < array.length / 2; i++) {
                char temp = array[i];
                array[i] = array[array.length - 1 - i];
                array[array.length - 1 - i] = temp;
            }
            str = new String(array);
            System.out.println(str);
        }
    }

    8、编写代码实现,从一个标准url里取出文件的扩展名,尽可能高效。

    public static void main(String[] args) {
            String str = fileExtNameFromUrl("http://localhost:8080/testweb/index.html");
            System.out.println(str);
        }
        
        public static String fileExtNameFromUrl(String url){
                                补充代码                  
        }
    public static void main(String[] args) {
            String str = fileExtNameFromUrl("http://localhost:8080/testweb/index.html");
            System.out.println(str);
        }
        
        public static String fileExtNameFromUrl(String url){
            return url.substring(url.lastIndexOf('.')+1);
        }

    9、有一个字符串String abc = “342567891”,请写程序将字符串abc进行升序,可以使用JDK API中的现有的功能方法。

    参考答案一:
    public class Test {
        public static void main(String[] args) {
            String str = "342567891";
            char[] arr = str.toCharArray();
            Arrays.sort(arr);
            str = new String(arr);
            System.out.println(str);
        }
    }

    10、编写一个懒汉式单例设计模式

    答案一:懒汉式形式一
    public class Singleton {
        private static Singleton instance;
        private Singleton(){
            
        }
        public static Singleton getInstance(){
            if(instance == null){
                synchronized (Singleton.class) {
                    if(instance == null){
                        instance = new Singleton();
                    }
                }
            }
            return instance;
        }
    }
    答案一:懒汉式形式二
    public class Singleton{
        private Singleton(){
            
        }
        private static class Inner{
            private static final Singleton INSTANCE = new Singleton();
        }
        
        public static Singleton getInstance(){
            return Inner.INSTANCE;
        }
    }

    11、请编写一个饿汉式单例设计模式

    答案一:饿汉式形式一
    public class Singleton {
        public static final Singleton INSTANCE = new Singleton();
        private Singleton(){
        }
    }
    答案二:饿汉式形式二
    public class Singleton {
        private static final Singleton INSTACNE = new Singleton();
        private Singleton(){
            
        }
        public static Singleton getInstance(){
            return INSTACNE;
        }
    }
    答案三:饿汉式形式三
    public enum Singleton {
        INSTANCE
    }

    12、补充如下枚举类型的代码,使得如下代码达到运行效果

    单词提示:monday,tuesday,wednesday,thursday,friday,saturday,sunday

    import java.util.Scanner;
    
    public class TestWeek {
    
        public static void main(String[] args) {
            Scanner input = new Scanner(System.in);
            System.out.print("今天是星期几(1-7):");
            int number = input.nextInt();//假设输入的是2
            Week w = Week.getByNumber(number);
            System.out.println("今天是:" + w);//今天是:TUESDAY(2,星期二)
        }
    
    }
    enum Week{
                            (1private int number;
        private String decription;
        
        private Week(int number, String decription) {
            this.number = number;
            this.decription = decription;
        }
        
        public static Week getByNumber(int number){
                            (2)                   
        }
    
        @Override
        public String toString() {
            return super.toString()+"(" + number + ","+ decription + ")";
        }
    }
    答案:
    enum Week{
        MONDAY(1,"星期一"),
        TUESDAY(2,"星期二"),
        WEDNESDAY(3,"星期三"),
        THURSDAY(4,"星期四"),
        FRIDAY(5,"星期五"),
        SATURDAY(6,"星期六"),
        SUNDAY(7,"星期日");
        
        private int number;
        private String decription;
        
        private Week(int number, String decription) {
            this.number = number;
            this.decription = decription;
        }
        
        public static Week getByNumber(int number){
            switch(number){
            case 1:
                return MONDAY;
            case 2:
                return TUESDAY;
            case 3:
                return WEDNESDAY;
            case 4:
                return THURSDAY;
            case 5:
                return FRIDAY;
            case 6:
                return SATURDAY;
            case 7:
                return SUNDAY;
            default:
                return null;
            }
        }
    
        @Override
        public String toString() {
            return super.toString()+"(" + number + ","+ decription + ")";
        }
    }

    13、写一段代码实现在遍历ArrayList时移除一个元素,例如:java

    import java.util.ArrayList;
    import java.util.Iterator;
    
    public class Test {
    
        public static void main(String[] args) {
            ArrayList<String> list = new ArrayList<String>();
            list.add("hello");
            list.add("java");
            list.add("world");
    
                              补充代码                         
        }
    }
    答案:
    import java.util.ArrayList;
    import java.util.Iterator;
    
    public class Test {
    
        public static void main(String[] args) {
            ArrayList<String> list = new ArrayList<String>();
            list.add("hello");
            list.add("java");
            list.add("world");
    
            Iterator<String> iterator = list.iterator();
            while (iterator.hasNext()) {
                String next = iterator.next();
                if ("java".equals(next)) {
                    iterator.remove();
                }
            }
        }
    }

    14、把如下信息添加到Map中,并遍历显示,请正确指定泛型

    浙江省
        绍兴市
        温州市
        湖州市
        嘉兴市
        台州市
        金华市
        舟山市
        衢州市
        丽水市
    海南省
        海口市
        三亚市
    北京市
        北京市
    参考答案一:
    import java.util.Arrays;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map.Entry;
    import java.util.Set;
    
    public class Test {
    
        public static void main(String[] args) throws Exception {
            HashMap<String,List<String>> map = new HashMap<String,List<String>>();
            map.put("北京市", Arrays.asList("北京市"));
            map.put("海南省", Arrays.asList("海口市","三亚市"));
            map.put("浙江省", Arrays.asList("绍兴市","温州市","湖州市","嘉兴市","台州市","金华市","舟山市","衢州市","丽水市"));
        
            Set<Entry<String, List<String>>> entrySet = map.entrySet();
            for (Entry<String, List<String>> entry : entrySet) {
                System.out.println(entry.getKey());
                List<String> value = entry.getValue();
                for (String string : value) {
                    System.out.println("\t" + string);
                }
            }
        }
    }
    参考答案二:
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.Map.Entry;
    import java.util.Set;
    
    public class Test {
    
        public static void main(String[] args) throws Exception {
            HashMap<String,ArrayList<String>> map = new HashMap<String,ArrayList<String>>();
            
            ArrayList<String> bj = new ArrayList<String>();
            bj.add("北京市");
            map.put("北京市", bj);
            
            ArrayList<String> hn = new ArrayList<String>();
            hn.add("海口市");
            hn.add("三亚市");
            map.put("海南省", hn);
            
            ArrayList<String> zj = new ArrayList<String>();
            zj.add("绍兴市");
            zj.add("温州市");
            zj.add("湖州市");
            zj.add("嘉兴市");
            zj.add("台州市");
            zj.add("金华市");
            zj.add("舟山市");
            zj.add("衢州市");
            zj.add("丽水市");
            map.put("浙江省", zj);
        
            Set<Entry<String, ArrayList<String>>> entrySet = map.entrySet();
            for (Entry<String, ArrayList<String>> entry : entrySet) {
                System.out.println(entry.getKey());
                ArrayList<String> value = entry.getValue();
                for (String string : value) {
                    System.out.println("\t" + string);
                }
            }
        }
    }
    参考答案三:
    import java.util.HashSet;
    import java.util.HashMap;
    import java.util.Map.Entry;
    import java.util.Set;
    
    public class Test {
    
        public static void main(String[] args) throws Exception {
            HashMap<String,HashSet<String>> map = new HashMap<String,HashSet<String>>();
            
            HashSet<String> bj = new HashSet<String>();
            bj.add("北京市");
            map.put("北京市", bj);
            
            HashSet<String> hn = new HashSet<String>();
            hn.add("海口市");
            hn.add("三亚市");
            map.put("海南省", hn);
            
            HashSet<String> zj = new HashSet<String>();
            zj.add("绍兴市");
            zj.add("温州市");
            zj.add("湖州市");
            zj.add("嘉兴市");
            zj.add("台州市");
            zj.add("金华市");
            zj.add("舟山市");
            zj.add("衢州市");
            zj.add("丽水市");
            map.put("浙江省", zj);
        
            Set<Entry<String, HashSet<String>>> entrySet = map.entrySet();
            for (Entry<String, HashSet<String>> entry : entrySet) {
                System.out.println(entry.getKey());
                HashSet<String> value = entry.getValue();
                for (String string : value) {
                    System.out.println("\t" + string);
                }
            }
        }
    }

    15、完成在如下Map中查询城市信息

    已知有省份Provice类型,有属性省份编号id和名称name,有城市City类型,有属性城市编号id和名称name,所属省份编号pid,以及所有信息现保存在一个Map中,现在要在map中,根据省份编号,查找这个省份下所有的城市。

    1:北京市
        1:北京市
    2:海南省
        1:海口市
        2:三亚市
    3:浙江省
        1:绍兴市
        2:温州市
        7:舟山市
        8:衢州市
        9:丽水市
        5:台州市
        4:嘉兴市
        6:金华市
        3:湖州市
    import java.util.HashSet;
    import java.util.HashMap;
    import java.util.Set;
    
    public class AreaManager {
        private HashMap<Province,HashSet<City>> map;
        
        public AreaManager(){
            map = new HashMap<Province,HashSet<City>>();
                    
            HashSet<City> bj = new HashSet<City>();
            bj.add(new City(1,"北京市",1));
            map.put(new Province(1,"北京市"), bj);
            
            HashSet<City> hn = new HashSet<City>();
            hn.add(new City(1,"海口市",2));
            hn.add(new City(2,"三亚市",2));
            map.put(new Province(2,"海南省"), hn);
            
            HashSet<City> zj = new HashSet<City>();
            zj.add(new City(1,"绍兴市",3));
            zj.add(new City(2,"温州市",3));
            zj.add(new City(3,"湖州市",3));
            zj.add(new City(4,"嘉兴市",3));
            zj.add(new City(5,"台州市",3));
            zj.add(new City(6,"金华市",3));
            zj.add(new City(7,"舟山市",3));
            zj.add(new City(8,"衢州市",3));
            zj.add(new City(9,"丽水市",3));
            map.put(new Province(3,"浙江省"), zj);
        }
        
        public HashSet<City> findCity(int pid){
                        补充代码                     
        }
    }
    参考答案:
        public HashSet<City> findCity(int pid){
            Set<Province> keySet = map.keySet();
            for (Province province : keySet) {
                if(province.getId() == pid){
                    return map.get(province);
                }
            }
            return null;
        }

    16、请编写代码读取一个项目根目录下info.properties文件

    里面的内容有user=atguigu等,请获取uservalue中,并在控制台打印

    import java.io.FileInputStream;
    import java.io.IOException;
    import java.util.Properties;
    
    public class Test{
        public static void main(String[] args) throws IOException {
            Properties pro = new Properties();
            
            //相对于bin
    //        pro.load(ClassLoader.getSystemResourceAsStream("info.properties"));
            
            //相对于项目根目录
            pro.load(new FileInputStream("info.properties"));
        
            String username = pro.getProperty("user");
            System.out.println(username);
        }
    }

    17、请编写代码把一个GBK的文本文件内容读取后存储到一个UTF-8的文本文件中。

    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    
    public class Test {
    
        public static void main(String[] args) throws Exception {
            FileInputStream fis = new FileInputStream("test_gbk.txt");
            InputStreamReader isr = new InputStreamReader(fis, "GBK");
    
            FileOutputStream fos = new FileOutputStream("test_utf8.txt");
            OutputStreamWriter oos = new OutputStreamWriter(fos, "UTF-8");
    
            char[] data = new char[10];
            int len;
            while ((len = isr.read(data)) != -1) {
                oos.write(data, 0, len);
            }
    
            isr.close();
            fis.close();
            oos.close();
            fos.close();
        }
    }

    18、用实现Runnable接口的方式,启动一个线程完成在线程中打印1-100的数字

    答案一:
    public class Test {
    
        public static void main(String[] args) {
            PrintNumberRunnable p = new PrintNumberRunnable();
            Thread t = new Thread(p);
            t.start();
        }
    
    }
    class PrintNumberRunnable implements Runnable{
    
        @Override
        public void run() {
            for(int i=1; i<=100; i++){
                System.out.println("i=" + i);
            }
        }
        
    }
    答案二:
    public class Test {
    
        public static void main(String[] args) {
            new Thread(new Runnable(){
                    @Override
                    public void run() {
                        for(int i=1; i<=100; i++){
                            System.out.println("i=" + i);
                        }
                    }
            }).start();
        }
    }
  • 相关阅读:
    004-Shell 基本运算符、算术运算符、关系运算符、布尔运算符、辑运算符、字符串运算符、文件测试运算符
    003-shell 传递参数
    002-shell变量定义、使用、字符串替换,分隔,搜索、数组、注释
    【Java】验证码识别解决方案
    bufferedimage 转换成 inputstream并保存文件
    遍历json对象---Java
    【网络爬虫】Httpclient4.X中使用HTTPS的方法采集12306网站
    httpclient获取cookies
    驾考宝典排行榜之爬虫接口解决方案
    java去除字符串中的空格、回车、换行符、制表符
  • 原文地址:https://www.cnblogs.com/LzMingYueShanPao/p/14577712.html
Copyright © 2020-2023  润新知