码迷,mamicode.com
首页 > 编程语言 > 详细

代码与编程(java基础)

时间:2017-09-29 23:07:50      阅读:258      评论:0      收藏:0      [点我收藏+]

标签:please   current   dex   执行顺序   改变   com   win   键盘   lease   

代码与编程(面试与笔试java)

1.写一个Singleton出来
Singleton模式主要作用是保证在Java应用程序中,一个类Class只有一个实例存在。
一般Singleton模式通常有几种种形式:

 1 public class Singleton {
 2     //第一种形式: 定义一个类,它的构造函数为private的,它有一个static的private的该类变量,在类初始化时实例话,通过一个public的getInstance方法获取对它的引用,继而调用其中的方法。
 3     private Singleton(){}
 4       //在自己内部定义自己一个实例,是不是很奇怪?
 5       //注意这是private 只供内部调用
 6        private static Singleton instance = new Singleton();
 7       //这里提供了一个供外部访问本class的静态方法,可以直接访问  
 8       public static Singleton getInstance() {
 9             return instance;   
10       } 
11   } 
12   //第二种形式: 
13   public class Singleton { 
14       private static Singleton instance = null;
15       public static synchronized Singleton getInstance() {
16      //这个方法比上面有所改进,不用每次都进行生成对象,只是第一次     
17      //使用时生成实例,提高了效率!
18         if (instance==null)
19             instance=new Singleton();
20         return instance;   } 
21     }     

 

其他形式:
定义一个类,它的构造函数为private的,所有方法为static的。
一般认为第一种形式要更加安全些 

 

2.继承时候类的执行顺序问题,一般都是选择题,问你将会打印出什么?


父类:

package test;
public class  FatherClass
{
    public FatherClass()
    {
     System.out.println("FatherClass Create");
 }

子类:

package test;
import test.FatherClass;
public class  ChildClass extends FatherClass
{
    public ChildClass()
    {
        System.out.println("ChildClass Create");
    }
    public static void main(String[] args) 
    {
        FatherClass fc = new FatherClass();
        ChildClass cc = new ChildClass();
    }
}

输出结果:
FatherClass Create
FatherClass Create
ChildClass Create

 

3.Java 的通信编程,编程题(或问答),用JAVA SOCKET编程,读服务器几个字符,再写入本地显示?


Server端程序:

 

package test;
import java.net.*;
import java.io.*; 
public class Server
{
    private ServerSocket ss;
    private Socket socket;
    private BufferedReader in;
    private PrintWriter out;
    public Server()
    {
        try
        {
            ss=new ServerSocket(10000);
            while(true)
            {
                socket = ss.accept();
                String RemoteIP = socket.getInetAddress().getHostAddress();
                String RemotePort = ":"+socket.getLocalPort();
                System.out.println("A client come in!IP:"+RemoteIP+RemotePort);
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                String line = in.readLine();
                System.out.println("Cleint send is :" + line);
                out = new PrintWriter(socket.getOutputStream(),true);
                out.println("Your Message Received!");
                out.close();
                in.close();
                socket.close();
            }
        }catch (IOException e)
        {
            out.println("wrong");
        }
    }
    public static void main(String[] args)
    {
        new Server();
    }
};

 

Client端程序:

 1 package test;
 2 import java.io.*;
 3 import java.net.*; 
 4 public class Client
 5 {
 6     Socket socket;
 7     BufferedReader in;
 8     PrintWriter out;
 9     public Client()
10     {
11         try
12         {
13             System.out.println("Try to Connect to 127.0.0.1:10000");
14             socket = new Socket("127.0.0.1",10000);
15             System.out.println("The Server Connected!");
16             System.out.println("Please enter some Character:");
17             BufferedReader line = new BufferedReader(new 
18                 InputStreamReader(System.in));
19             out = new PrintWriter(socket.getOutputStream(),true);
20             out.println(line.readLine());
21             in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
22             System.out.println(in.readLine());
23             out.close();
24             in.close();
25             socket.close();
26         }catch(IOException e)
27         {
28             out.println("Wrong");
29         }
30     }
31     public static void main(String[] args)
32     {
33         new Client();
34     }
35 }; 

 

 

4.可能会让你写一段Jdbc连Oracle的程序,并实现数据查询.

 

 1 package hello.ant;
 2 import java.sql.*;
 3 public class  jdbc
 4 {
 5     String dbUrl="jdbc:oracle:thin:@127.0.0.1:1521:orcl";
 6     String theUser="admin";
 7     String thePw="manager";
 8     Connection c=null;
 9     Statement conn;
10     ResultSet rs=null;
11     public jdbc() 
12     {
13         try{
14             Class.forName("oracle.jdbc.driver.OracleDriver").newInstance(); 
15             c = DriverManager.getConnection(dbUrl,theUser,thePw);
16             conn=c.createStatement();
17         }catch(Exception e){
18             e.printStackTrace();
19         }
20     }
21     public boolean executeUpdate(String sql)
22     {
23         try
24         {
25             conn.executeUpdate(sql);
26             return true;
27         }
28         catch (SQLException e)
29         {
30             e.printStackTrace();
31             return false;
32         }
33     }
34     public ResultSet executeQuery(String sql)
35     {
36         rs=null;
37         try
38         {
39             rs=conn.executeQuery(sql);
40         }
41         catch (SQLException e)
42         {
43             e.printStackTrace();
44         }
45         return rs;
46     }
47     public void close()
48     {
49         try
50         {
51             conn.close();
52             c.close();
53         }
54         catch (Exception e)
55         {
56             e.printStackTrace();
57         }
58     }
59     public static void main(String[] args)
60     {
61         ResultSet rs;
62         jdbc conn = new jdbc();
63         rs=conn.executeQuery("select * from test");
64         try{
65             while (rs.next())
66             {
67                 System.out.println(rs.getString("id"));
68                 System.out.println(rs.getString("name"));
69             }
70         }catch(Exception e)
71         {
72             e.printStackTrace();
73         }
74     }
75 } 

 

 

5.将一个键盘输入的数字转化成中文输出
(例如:输入:1234567     输出:一百二拾三万四千五百六拾七)

用java语言实现,,请编一段程序实现!

  1 public class Reader {
  2     private String strNum;
  3     private String strNumChFormat;
  4     private String strNumTemp;
  5     private int intNumLen;
  6     private String strBegin;
  7     public Reader(String strNum) {
  8         this.strNum = strNum;
  9     }
 10     public boolean check(String strNum) {
 11         boolean valid = false;
 12         
 13         if (strNum.substring(0,1).equals("0")){
 14             this.strNum = strNum.substring(1);
 15         }
 16         try {
 17             new Double(strNum);
 18             valid = true;
 19         }
 20         catch (NumberFormatException ex) {
 21             System.out.println("Bad number format!");
 22         }
 23         return valid;
 24     }
 25     public void init() {
 26         strNumChFormat = "";
 27         intNumLen = strNum.length();
 28         strNumTemp = strNum;
 29         strNumTemp = strNumTemp.replace(‘1‘, ‘一‘);
 30         strNumTemp = strNumTemp.replace(‘2‘, ‘二‘);
 31         strNumTemp = strNumTemp.replace(‘3‘, ‘三‘);
 32         strNumTemp = strNumTemp.replace(‘4‘, ‘四‘);
 33         strNumTemp = strNumTemp.replace(‘5‘, ‘五‘);
 34         strNumTemp = strNumTemp.replace(‘6‘, ‘六‘);
 35         strNumTemp = strNumTemp.replace(‘7‘, ‘七‘);
 36         strNumTemp = strNumTemp.replace(‘8‘, ‘八‘);
 37         strNumTemp = strNumTemp.replace(‘9‘, ‘九‘);
 38         strNumTemp = strNumTemp.replace(‘0‘, ‘零‘);
 39         strNumTemp = strNumTemp.replace(‘.‘, ‘点‘);
 40         strBegin = strNumTemp.substring(0, 1);
 41     }
 42     public String readNum() {
 43         if (check(strNum)) {
 44             init();
 45             try {
 46                 for (int i = 1, j = 1, k = 1; i < intNumLen; i++) {
 47                     if (strNumTemp.charAt(intNumLen - 1) == ‘零‘ && i == 1) {
 48                         strNumChFormat = "位";
 49                     }
 50                     else if (strNumTemp.charAt(intNumLen - i) == ‘零‘ && j == 1) {
 51                         strNumChFormat = "位" + strNumChFormat;
 52                     }
 53                     else if (strNumTemp.charAt(intNumLen - i) == ‘点‘) {
 54                         j = 1;
 55                         k = 1;
 56                         strNumChFormat = strNumTemp.charAt(intNumLen - i) + strNumChFormat;
 57                         continue;
 58                     }
 59                     else {
 60                         strNumChFormat = strNumTemp.charAt(intNumLen - i) + strNumChFormat;
 61                     }
 62                     if (strNumTemp.charAt(intNumLen - i - 1) != ‘位‘ &&
 63                         strNumTemp.charAt(intNumLen - i - 1) != ‘零‘) {
 64                         if (j == 1 && i < intNumLen) {
 65                             strNumChFormat = ‘拾‘ + strNumChFormat;
 66                         }
 67                         else if (j == 2 && i < intNumLen) {
 68                             strNumChFormat = ‘百‘ + strNumChFormat;
 69                         }
 70                         else if (j == 3 && i < intNumLen) {
 71                             strNumChFormat = ‘千‘ + strNumChFormat;
 72                         }
 73                     }
 74                     if (j == 4 && i < intNumLen) {
 75                         j = 0;
 76                     }
 77                     if (k == 4 && i < intNumLen) {
 78                         strNumChFormat = ‘万‘ + strNumChFormat;
 79                     }
 80                     else if (k == 8 && i < intNumLen) {
 81                         k = 0;
 82                         strNumChFormat = ‘亿‘ + strNumChFormat;
 83                     }
 84                     j++;
 85                     k++;
 86                 }
 87                 while (strNumChFormat.indexOf("位") != -1) {
 88                     strNumChFormat = strNumChFormat.replaceAll("位", " ");
 89                 }
 90                 if (strNumChFormat.substring(0, 2) == "一拾") {
 91                     strNumChFormat = strNumChFormat.substring(1, strNumChFormat.length());
 92                 }
 93                 if (strNumChFormat.indexOf("点") >= 0) {
 94                     String rebegin = strNumChFormat.substring(0,
 95                         strNumChFormat.indexOf("点"));
 96                     String relast = strNumChFormat.substring(strNumChFormat.indexOf("点"),
 97                         strNumChFormat.length());
 98                     for (int i = 1; i <= relast.length(); i++) {
 99                         relast = relast.replaceAll("拾", "");
100                         relast = relast.replaceAll("百", "");
101                         relast = relast.replaceAll("千", "");
102                         relast = relast.replaceAll("万", "");
103                         relast = relast.replaceAll("亿", "");
104                     }
105                     strNumChFormat = rebegin + relast;
106                 }
107             }
108             catch (ArrayIndexOutOfBoundsException ex) {
109                 ex.printStackTrace();
110             }
111             catch (Exception ex) {
112                 ex.printStackTrace();
113             }
114             int off = strNumChFormat.indexOf("点");
115             strNumChFormat = strBegin + strNumChFormat.substring(0);
116         }
117         else {
118             strNumChFormat = "";
119         }
120         return strNumChFormat;
121     }
122     public static void main(String args[]) {
123         try {
124             String number = args[0].toString();
125             System.out.println("The number is: " + number);
126             Reader reader = new Reader(number);
127             System.out.println("Output String: " + reader.readNum());
128         }
129         catch (Exception ex) {
130             System.out.println("Please input like that: javac Reader <number>");
131         }
132     }
133 } 

 

6.设计4个线程,其中两个线程每次对j增加1,另外两个线程对j每次减少1。写出程序。
以下程序使用内部类实现线程,对j增减的时候没有考虑顺序问题

 1 public class ThreadTest1{
 2     private int j;
 3     public static void main(String args[]){
 4         ThreadTest1 tt=new ThreadTest1();
 5         Inc inc=tt.new Inc();
 6         Dec dec=tt.new Dec();
 7         for(int i=0;i<2;i++){
 8             Thread t=new Thread(inc);
 9             t.start();
10             t=new Thread(dec);
11             t.start();
12         }
13     }
14     private synchronized void inc(){
15         j++;
16         System.out.println(Thread.currentThread().getName()+"-inc:"+j);
17     }
18     private synchronized void dec(){
19         j--;
20         System.out.println(Thread.currentThread().getName()+"-dec:"+j);
21     }
22     class Inc implements Runnable{
23         public void run(){
24             for(int i=0;i<100;i++){
25                 inc();
26             }
27         }
28     }
29     class Dec implements Runnable{
30         public void run(){
31             for(int i=0;i<100;i++){
32                 dec();
33             }
34         }
35     }
36 } 

 

7.JAVA代码查错
1.

abstract class Name {
   private String name;
   public abstract boolean isStupidName(String name) {}
}
答案: 错。abstract method必须以分号结尾,且不带花括号。


2.
public class Something {
   void doSomething () {
       private String s = "";
       int l = s.length();
   }
}
有错吗?
答案: 错。局部变量前不能放置任何访问修饰符 (private,public,和protected)。final可以用来修饰局部变量
(final如同abstract和strictfp,都是非访问修饰符,strictfp只能修饰class和method而非variable)。


3.
abstract class Something {
   private abstract String doSomething ();
}
这好像没什么错吧?
答案: 错。abstract的methods不能以private修饰。abstract的methods就是让子类implement(实现)具体细节的,怎么可以用private把abstract
method封锁起来呢? (同理,abstract method前不能加final)。


4.
public class Something {
   public int addOne(final int x) {
       return ++x;
   }
}
这个比较明显。
答案: 错。int x被修饰成final,意味着x不能在addOne method中被修改。


5.
public class Something {
   public static void main(String[] args) {
       Other o = new Other();
       new Something().addOne(o);
   }
   public void addOne(final Other o) {
       o.i++;
   }
}
class Other {
   public int i;
}
和上面的很相似,都是关于final的问题,这有错吗?
答案: 正确。在addOne method中,参数o被修饰成final。如果在addOne method里我们修改了o的reference
(比如: o = new Other();),那么如同上例这题也是错的。但这里修改的是o的member vairable
(成员变量),而o的reference并没有改变。


6.
class Something {
    int i;
    public void doSomething() {
        System.out.println("i = " + i);
    }

有什么错呢? 看不出来啊。
答案: 正确。输出的是"i = 0"。int i属於instant variable (实例变量,或叫成员变量)。instant variable有default value。int的default value是0。


7.
class Something {
    final int i;
    public void doSomething() {
        System.out.println("i = " + i);
    }
}
和上面一题只有一个地方不同,就是多了一个final。这难道就错了吗?
答案: 错。final int i是个final的instant variable (实例变量,或叫成员变量)。final的instant variable没有default value,必须在constructor (构造器)结束之前被赋予一个明确的值。可以修改为"final int i = 0;"。


8.
public class Something {
     public static void main(String[] args) {
        Something s = new Something();
        System.out.println("s.doSomething() returns " + doSomething());
    }
    public String doSomething() {
        return "Do something ...";
    }
}
 看上去很完美。
答案: 错。看上去在main里call doSomething没有什么问题,毕竟两个methods都在同一个class里。但仔细看,main是static的。static method不能直接call non-static methods。可改成"System.out.println("s.doSomething() returns " + s.doSomething());"。同理,static method不能访问non-static instant variable。

 

9.
此处,Something类的文件名叫OtherThing.java
class Something {
    private static void main(String[] something_to_do) {        
        System.out.println("Do something ...");
    }
}
 这个好像很明显。
答案: 正确。从来没有人说过Java的Class名字必须和其文件名相同。但public class的名字必须和文件名相同。


10.
interface  A{
   int x = 0;
}
class B{
   int x =1;
}
class C extends B implements A {
   public void pX(){
      System.out.println(x);
   }
   public static void main(String[] args) {
      new C().pX();
   }
}
答案:错误。在编译时会发生错误(错误描述不同的JVM有不同的信息,意思就是未明确的x调用,两个x都匹配(就象在同时import java.util和java.sql两个包时直接声明Date一样)。对于父类的变量,可以用super.x来明确,而接口的属性默认隐含为 public static final.所以可以通过A.x来明确。


11.
interface Playable {
    void play();
}
interface Bounceable {
    void play();
}
interface Rollable extends Playable, Bounceable {
    Ball ball = new Ball("PingPang");
}
class Ball implements Rollable {
    private String name;
    public String getName() {
        return name;
    }
    public Ball(String name) {
        this.name = name;        
    }
   public void play() {
        ball = new Ball("Football");
        System.out.println(ball.getName());
    }
}
这个错误不容易发现。
答案: 错。"interface Rollable extends Playable, Bounceable"没有问题。interface可继承多个interfaces,所以这里没错。问题出在interface Rollable里的"Ball ball = new Ball("PingPang");"。任何在interface里声明的interface variable (接口变量,也可称成员变量),默认为public static final。也就是说"Ball ball = new Ball("PingPang");"实际上是"public static final Ball ball = new Ball("PingPang");"。在Ball类的Play()方法中,"ball = new Ball("Football");"改变了ball的reference,而这里的ball来自Rollable interface,Rollable interface里的ball是public static final的,final的object是不能被改变reference的。因此编译器将在"ball = new Ball("Football");"这里显示有错。

 

代码与编程(java基础)

标签:please   current   dex   执行顺序   改变   com   win   键盘   lease   

原文地址:http://www.cnblogs.com/swifthua/p/7612826.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!