JAVA面试程序题

一、

1、请用Java写一个冒泡排序方法

【参考答案】

public static void Bubble(int a[]){

for(int i=0;i

for(int j=a.length-1;j>i;j–){

if(a[j]

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

a[j-1]=a[j]-a[j-1];

a[j]=a[j]-a[j-1];

}

}

}

}

2、子线程循环10次,接着主线程循环100,接着又回到子线程循环10次,接着再回到主线程又循环100,如此循环50次,请写出程序。

【参考答案】

最终的程序代码如下:

public class ThreadTest {

/**

* @param args

*/

public static void main(String[] args) {

// TODO Auto-generated method stub

new ThreadTest().init();

}

public void init()

{

final Business business = new Business();

new Thread(

new Runnable()

{

public void run() {

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

{

business.SubThread(i);

}

}

}

).start();

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

{

business.MainThread(i);

}

}

private class Business

{

boolean bShouldSub = true;//这里相当于定义了控制该谁执行的一个信号灯

public synchronized void MainThread(int i)

{

if(bShouldSub)

try {

this.wait();

}catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

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

{

System.out.println(Thread.currentThread().getName() + “:i=” + i +”,j=” + j);

}

bShouldSub= true;

this.notify();

}

public synchronized void SubThread(int i)

{

if(!bShouldSub)

try {

this.wait();

}catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

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

{

System.out.println(Thread.currentThread().getName() + “:i=” + i +”,j=” + j);

}

bShouldSub = false;

this.notify();

}

}

}

备注:不可能一上来就写出上面的完整代码,最初写出来的代码如下,问题在于两个线程的代码要参照同一个变量,即这两个线程的代码要共享数据,所以,把这两个线程的执行代码搬到同一个类中去:

package com.huawei.interview.lym;

public class ThreadTest {

private static booleanbShouldMain= false;

public static void main(String[] args) {

// TODO Auto-generated method stub

/*new Thread(){

public void run()

{

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

{

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

{

System.out.println(“i=” + i + “,j=” + j);

}

}

}

}.start();*/

//final String str = new String(“”);

new Thread(

new Runnable()

{

public void run()

{

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

{

synchronized (ThreadTest.class) {

if(bShouldMain)

{

try {

ThreadTest.class.wait();}

catch (InterruptedException e) {

e.printStackTrace();

}

}

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

{

System.out.println(

Thread.currentThread().getName() +

“i=” + i + “,j=” + j);

}

bShouldMain= true;

ThreadTest.class.notify();

}

}

}

}

).start();

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

{

synchronized (ThreadTest.class) {

if(!bShouldMain)

{

try {

ThreadTest.class.wait();}

catch (InterruptedException e) {

e.printStackTrace();

}

}

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

{

System.out.println(

Thread.currentThread().getName() +

“i=” + i + “,j=” + j);

}

bShouldMain= false;

ThreadTest.class.notify();

}

}

}

}

下面使用jdk5中的并发库来实现的:

import java.util.concurrent.Executors;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.locks.Lock;

import java.util.concurrent.locks.ReentrantLock;

import java.util.concurrent.locks.Condition;

public class ThreadTest

{

private static Lock lock = new ReentrantLock();

private static Condition subThreadCondition = lock.newCondition();

private static boolean bBhouldSubThread = false;

public static void main(String [] args)

{

ExecutorService threadPool = Executors.newFixedThreadPool(3);

threadPool.execute(new Runnable(){

public void run()

{

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

{

lock.lock();

try

{

if(!bBhouldSubThread)

subThreadCondition.await();

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

{

System.out.println(Thread.currentThread().getName() + “,j=” + j);

}

bBhouldSubThread = false;

subThreadCondition.signal();

}catch(Exception e)

{

}

finally

{

lock.unlock();

}

}

}

});

threadPool.shutdown();

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

{

lock.lock();

try

{

if(bBhouldSubThread)

subThreadCondition.await();

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

{

System.out.println(Thread.currentThread().getName() + “,j=” + j);

}

bBhouldSubThread = true;

subThreadCondition.signal();

}catch(Exception e)

{

}

finally

{

lock.unlock();

}

}

}

3、写一个程序,把一个文件的数组按对角线做对称变换,并输出!

【参考答案】

一个正方形里面全数字,写一个程序,成对角线转变!我做的这个是3行3列的对角互换,也许转换规则不一样

public class testMain {

public static void main(String[] args) {

int a[][]=new int[3][3];

int c=1;

//初始化数据

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

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

a[i][j]=c++;

}

}

System.out.println(“转换之前:”);

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

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

System.out.print(“a[“+i+”][“+j+”]=”+a[i][j]+”   “);

}

System.out.println(“\n”);

}

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

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

if((i+1<3&&j+1<3)&&i==j&&i!=0&&i!=3-i){

int temp=a[i-1][j-1];

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

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

temp=a[i-1][j+1];

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

a[i+1][j-1]=temp;

}

}

}

System.out.println(“转换之后:”);

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

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

System.out

print(“a[“+i+”][“+j+”]=”+a[i][j]+”   “);

}

System.out.println(“\n”);

}

}

}

4、写一个方法,传入一个int型的数字,把它的四个字节码取出来,并且把它按大小顺序通过控制台输出?

【参考答案】

public static void main(String[] args) {

int num = -800000000;

String str = Integer.toBinaryString(num); //获得num的二进制

if(num>=0) {    //如果输入的数为正数,位数可能不足32位,要补0;负数肯定是32位

if(str.length()<32) { //二进制不足32位,就在前面补0

int n0 = 32-str.length(); //看差几个0

String temp = “”;

for(int i=0;i

temp = temp + “0”; //拼0

}

str = temp + str;

}

}

String s1 = str.substring(0, 8);

String s2 = str.substring(8, 16);

String s3 = str.substring(16, 24);

String s4 = str.substring(24, 32);

System.out.println(str);

System.out.println(s1);

System.out.println(s2);

System.out.println(s3);

System.out.println(s4);

int n1=Integer.parseInt(s1,2);//以二进制把字符串解析为10进制的数

int n2=Integer.parseInt(s2,2);

int n3=Integer.parseInt(s3,2);

int n4=Integer.parseInt(s4,2);

System.out.println(n1);

System.out.println(n2);

System.out.println(n3);

System.out.println(n4);        //整数大小自己比较吧

}

【分析】

5、设计4个线程,其中两个线程每次对j增加1,另外两个线程对j每次减少1。写出程序。

【参考答案】

以下程序使用内部类实现线程,对j增减的时候没有考虑顺序问题。

public class ThreadTest1

{

private int j;

public static void main(String args[]){

ThreadTest1 tt=new ThreadTest1();

Inc inc=tt.new Inc();

Dec dec=tt.new Dec();

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

Thread t=new Thread(inc);

t.start();

t=new Thread(dec);

t.start();

}

}

private synchronized void inc(){

j++;

System.out.println(Thread.currentThread().getName()+”-inc:”+j);

}

private synchronized void dec(){

j–;

System.out.println(Thread.currentThread().getName()+”-dec:”+j);

}

class Inc implements Runnable{

public void run(){

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

inc();

}

}

}

class Dec implements Runnable{

public void run(){

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

dec();

}

}

}

}

———-随手再写的一个————-

class A

{

JManger j =new JManager();

main()

{

new A().call();

}

void call

{

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

{

new Thread(

new Runnable(){ public void run(){while(true){j.accumulate()}}}

).start();

new Thread(new Runnable(){ public void run(){while(true){j.sub()}}}).start();

}

}

}

class JManager

{

private j = 0;

public synchronized void subtract()

{

j–

}

public synchronized void accumulate()

{

j++;

}

}

6、十六进制的216转换十进制是多少?

216是16进制,转10进制:

=2*16^2+1*16^1+6*16^0

=512+16+6

=536

以下函数htoi函数的功能是将一个十六进制数字的字符串,转换成它等价的十进制整数值。

Public int htoi(char s[])

{

Int i , n ;

N=0;

For(i=0 , s[i]<’\0’;i++)

{

If(s[i]>=0&&s[i]<=9) n=_______

If(s[i]>=’a’&&s[i]<=’f’) n=_________

If(s[i]>=’A’&&s[i]<=’F’) n=_________

}

Return (n);

}

7、如何把一段逗号分割的字符串转换成一个数组?

【参考答案】

可以说说我的思路:

1.用正则表达式,代码大概为:String [] result = orgStr.split(“,”);

2.用StingTokenizer ,代码为:

StringTokenizer  tokener = StringTokenizer(orgStr,”,”);

String [] result = new String[tokener .countTokens()];

Int i=0;

while(tokener.hasNext(){result[i++]=toker.nextToken();}

8、编写一个函数将一个十六进制数的字符串参数转换成整数返回。

【参考答案】

String str =“13abf”;

int len = str.length;

int sum = 0;

for(int i=0;i

char c = str.charAt(len-1-i);

int n = Character.digit(c,16);

sum += n * (1<<(4*i));

}

其实,也可以用Integer.parseInt(str,16),但面试官很可能是想考我们的编码基本功。

9、读取一个文件在控制台打印出来

【参考答案】

File file =newFile(“E:\\JRadioButtonDemo.java”);

longfile_length= file.length();

try{

//输入流

FileInputStream input =newFileInputStream(file);

byteb_data [] =newbyte[(int)file_length];

input.read(b_data);

System.out.println(newString(b_data));

input.close();

}catch(FileNotFoundException e) {

//TODOAuto-generated catch block

e.printStackTrace();

}catch(IOException e) {

//TODOAuto-generated catch block

e.printStackTrace();

10、递归实现1,1,2,3,5,8,.30个数是多少?【上海菲耐德】

【参考答案】

public static int Foo(int i)

{

if (i <= 0)

return 0;

else if(i > 0 && i <= 2)

return 1;

else return Foo(i -1) + Foo(i – 2);

}

int i=Foo(30);

System.out.println(i);

11、求一个字符串中第一个无重复的字符

publicstaticvoidgetUniqueString(String str){

booleanbool =true;

for(inti=0;i

String s1 = str.substring(i, i+1);

if(str.indexOf(s1, i+1)==-1){

System.out.println(s1);

bool =false;

}

}

}

12、写一个递归函数,输入一个整数,反序输出这个整数

//写一个递归函数,输入一个整数,反序输出这个整数

publicstaticvoidprintOut(intn) {

System.out.print(n % 10);

if(n >= 10){

printOut(n / 10);

}

}

13、有一个数据文件:123 34  17  651234  345….这些数据都是随机产生的,编写程序读出该文件.并将其以从大到小的顺序输出到另一个文件中.

public void readtext(){

File file = new File(“D:\test.txt”);

List list= new ArrayList();

try {

BufferedReader br=new BufferedReader(new FileReader(file));

String data = “”;

String line = null;

while ( (line = br.readLine()) != null) {

data = data.concat(line);

}

StringTokenizer stoken = new StringTokenizer(data, ” “);

while (stoken.hasMoreTokens()) {

int i = Integer.parseInt(stoken.nextToken());

list.add(i);

}

}catch(Exception ex) {}

String[] str = new String[list.size()];

for(int i=0;i

str[i]=list.get(i);

}

Object iTemp= null;

for(int i=1;i

for(int j=list.size()-1;j>=i;j–) {

if(str[j]>str[j-1]) {

iTemp = str[j-1];

str[j-1] = str[j];

str[j] = iTemp;

}

}

String result = “”;

for(int i=0;i

result +=str[i]+” “;

}

//将result写入另外一个文件即可。

}

14、从一到十九共十九个数,打印出利用这十九个整数任意多个相加等于20所以可能性,每个数字在同一个算式中只出现一次.

public void test(){

Integer[] a = new Integer[19];

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

a[i-1]=i;

}

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

for(int j=18-i;j<18;j++)

if(a[i]+a[j]==20)

System.out.println(a[i]+”+”+a[i+1]+”=”+20);

}

}

15、一个字符串中可能存在A-Z的全角字符,写一个方法把里面的全角字符转变成半角字符?

答:采用建立字典表进行查找转换

public  static String translate(String s){

String qj = “ABCDEFGHIJKLMNOPQRSTUVWXYZ”;

String bj = “ABCDEFGHIJKLMNOPQRSTUVWXYZ”;

StringBuffer sb = new StringBuffer();

for(int i=0;i

char c = s.charAt(i);

int pos = qj.indexOf(c);

if(pos>=0){

System.out.println(c + “,” + pos);

sb.append(bj.charAt(pos));

}else{

sb.append(c);

}

}

return sb.toString();

}

16、Stack堆栈,实现进栈、出栈。【云巢动脉面试题】

package t1;

public class mystack {

private Object[] data;

private int top=-1;

private int size;

public mystack()

{

data=new Object[5];

size=5;

}

public mystack(int size)

{

data=new Object[size];

this.size=size;

}

public void push(Object obj)

{

if(this.isfull())

{

return ;

}

top++;

data[top]=obj;

}

public Object pop() {

if(this.isempty())

{

return null;

}

Object obj=data[top];

top–;

return obj ;

}

public boolean isfull()

{

if(top==data.length)

{

return true;

}

else

{

return false;

}

}

public boolean isempty()

{

if(top==-1)

{

return true;

}

else

{

return false;

}

}

}

17、定义两个变量ab,不使用第三个变量,使两个值交换

public class testMain {

public void test(int a,int b){

System.out.println(“交换前a = “+a);

System.out.println(“交换前b = “+b);

a=a+b;

b=a-b;

a=a-b;

System.out.println(“交换后a = ” +a);

System.out.print(“交换后b = “+b);

}

public static void main(String args[]){

new testMain().test(10,13);

}

}

18、针对一个分期付款,总期为1年,给定分期金额,期数和开始还款时间,计算出各期还款日期。

package demo;

import java.util.Calendar;

import java.util.Date;

public class TestDemo {

//分期付款,总期为1年,给定分期金额,期数和开始还款时间

//计算出各期还款日期

public void huankuan(double amount,int  num,Date start){

int period = 365/num; //一年中分期间隔天数

Calendar cal = Calendar.getInstance();

cal.set(Calendar.YEAR, start.getYear()+1900);

cal.set(Calendar.MONTH, start.getMonth());

cal.set(Calendar.DATE, start.getDate());

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

System.out.println(“第” + i + “期还款日期: ” + cal.getTime().toLocaleString());

cal.add(Calendar.DATE, period);

}

}

public static void main(String[] args) {

TestDemo demo = new TestDemo();

demo.huankuan(20000.00, 1, new Date());

}

}

19、用一个方法查出宜个数值类型数组的最大值,用递归方式实现。【高达软件】

方法1

public class Test1 {

public static int a(int[] i,int j){

if(i.length-1>j){

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

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

}

return a(i,j+1);

}else{

return i[i.length-1];

}

}

}

方法2  –非递归

public  static int  test(int  []num){

int x=0;

int log   =  num.Length;

for(intt=0;t

if(num[t]>x){

x=num[t];

}

}return  x;

}

方法3 —递归不改变原数组中的元素

public static int getMax(int[]a, int index,int max){

int len = a.length;

if(len==1){

return a[len-1];

}

if(index==0){

max = a[index];

}

if(index==len){

return max;

}

if(max

max = a[index];

}

index++;

return getMax(a,index,max);

}

//测试

int max = getMax(new int[]{2,5,18,3,38,10,2},0,0);

System.out.println(max);

20、C编写将一个100以内的自然数分解质因数

/*  100以内素数*/

#include

main()

{

int i,j;

for(i=2;i<100;i++)

{

for(j=2;j

{

if(i%j==0)

break;

}

if(i==j)

{

printf(“%d “,i);

}

}

}

/*分解质因数*/

main()

{

int   n,i;

printf( “please   input   a   number:\n “);

scanf( “%d “,&n);

printf( “%d= “,n);

for(i=2;i <=n;i++)

while(n!=i)

{

if(n%i==0)

{

printf( “%d* “,i);

n=n/i;

} else{break;}

}

printf( “%d “,n);

getch();

}

21、main方法中将字符串中的数字排序并输出STRING A=”56.89.5.3.75.98.98.26.15.44″

String s=”56.89.5.3.75.98.98.26.15.44”;

String s1[]=s. split (“.”);

Integer ii[]=new Integer[s1.length];

For(int i=0;i

ii[i]=Integer.parseInt(s1[i]);

}

Arrays.sort(ii);

for(Integer o: ii){

System.out.println(o+”s”);

}

22、40,用你所知道的数学方法计算出24

0的阶乘等于1即0!=1那么4个0就是4了

又4的阶乘为244!=24

23、判断身份证:要么是15位,要么是18位,最后一位可以为字母,并写程序提出其中的年月日。

答:我们可以用正则表达式来定义复杂的字符串格式,(\d{17}[0-9a-zA-Z]|\d{14}[0-9a-zA-Z])可以用来判断是否为合法的15位或18位身份证号码。

因为15位和18位的身份证号码都是从7位到第12位为身份证为日期类型。这样我们可以设计出更精确的正则模式,使身份证号的日期合法,这样我们的正则模式可以进一步将日期部分的正则修改为[12][0-9]{3}[01][0-9][123][0-9],当然可以更精确的设置日期。

在jdk的java.util.Regex包中有实现正则的类,Pattern和Matcher。以下是实现代码:

import java.util.regex.Matcher;

import java.util.regex.Pattern;

public class RegexTest {

/**

* @param args

*/

public static void main(String[] args) {

//测试是否为合法的身份证号码

String[] strs = { “130681198712092019”, “13068119871209201x”,

“13068119871209201”, “123456789012345”, “12345678901234x”,

“1234567890123” };

Pattern p1 = Pattern.compile(“(\\d{17}[0-9a-zA-Z]|\\d{14}[0-9a-zA-Z])”);

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

Matcher matcher = p1.matcher(strs[i]);

System.out.println(strs[i] + “:” + matcher.matches());

}

Pattern p2 = Pattern.compile(“\\d{6}(\\d{8}).*”); //用于提取出生日字符串

Pattern p3 = Pattern.compile(“(\\d{4})(\\d{2})(\\d{2})”);//用于将生日字符串进行分解为年月日

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

Matcher matcher = p2.matcher(strs[i]);

boolean b = matcher.find();

if (b) {

String s = matcher.group(1);

Matcher matcher2 = p3.matcher(s);

if (matcher2.find()) {

System.out

.println(“生日为” + matcher2.group(1) + “年”

+ matcher2.group(2) + “月”

+ matcher2.group(3) + “日”);

}

}

}

}

}

24、编写一个程序,将a.txt文件中的单词与b.txt文件中的单词交替合并到c.txt文件中,a.txt文件中的单词用回车符分隔,b.txt文件中用回车或空格进行分隔。

答:

package cn.itcast;

import java.io.File;

import java.io.FileReader;

import java.io.FileWriter;

public class MainClass{

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

FileManager a = new FileManager(“a.txt”,new char[]{‘\n’});

FileManager b = new FileManager(“b.txt”,new char[]{‘\n’,’ ‘});

FileWriter c = new FileWriter(“c.txt”);

String aWord = null;

String bWord = null;

while((aWord = a.nextWord()) !=null ){

c.write(aWord + “\n”);

bWord = b.nextWord();

if(bWord != null)

c.write(bWord + “\n”);

}

while((bWord = b.nextWord()) != null){

c.write(bWord + “\n”);

}

c.close();

}

}

class FileManager{

String[] words = null;

int pos = 0;

public FileManager(String filename,char[] seperators) throws Exception{

File f = new File(filename);

FileReader reader = new FileReader(f);

char[] buf = new char[(int)f.length()];

int len = reader.read(buf);

String results = new String(buf,0,len);

String regex = null;

if(seperators.length >1 ){

regex = “” + seperators[0] + “|” + seperators[1];

}else{

regex = “” + seperators[0];

}

words = results.split(regex);

}

public String nextWord(){

if(pos == words.length)

return null;

return words[pos++];

}

}

25、编写一个程序,将d:\java目录下的所有.java文件复制到d:\jad目录下,并将原来文件的扩展名从.java改为.jad

答:listFiles方法接受一个FileFilter对象,这个FileFilter对象就是过虑的策略对象,不同的人提供不同的FileFilter实现,即提供了不同的过滤策略。

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.FilenameFilter;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

public class Jad2Java {

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

File srcDir = new File(“java”);

if(!(srcDir.exists() && srcDir.isDirectory()))

throw new Exception(“目录不存在”);

File[] files = srcDir.listFiles(

new FilenameFilter(){

public boolean accept(File dir, String name) {

return name.endsWith(“.java”);

}

}

);

System.out.println(files.length);

File destDir = new File(“jad”);

if(!destDir.exists()) destDir.mkdir();

for(File f :files){

FileInputStream  fis = new FileInputStream(f);

String destFileName = f.getName().replaceAll(“\\.java$”, “.jad”);

FileOutputStream fos = new FileOutputStream(new File(destDir,destFileName));

copy(fis,fos);

fis.close();

fos.close();

}

}

private static void copy(InputStream ips,OutputStream ops) throws Exception{

int len = 0;

byte[] buf = new byte[1024];

while((len = ips.read(buf)) != -1){

ops.write(buf,0,len);

}

}

}

由本题总结的思想及策略模式的解析:

1.

class jad2java{

1.得到某个目录下的所有的java文件集合

1.1得到目录File srcDir = new File(“d:\\java”);

1.2得到目录下的所有java文件:File[] files = srcDir.listFiles(new MyFileFilter());

1.3只想得到.java的文件:class MyFileFilter implememyts FileFilter{

public boolean accept(File pathname){

return pathname.getName().endsWith(“.java”)

}

}

2.将每个文件复制到另外一个目录,并改扩展名

2.1得到目标目录,如果目标目录不存在,则创建之

2.2根据源文件名得到目标文件名,注意要用正则表达式,注意.的转义。

2.3根据表示目录的File和目标文件名的字符串,得到表示目标文件的File。

//要在硬盘中准确地创建出一个文件,需要知道文件名和文件的目录。

2.4将源文件的流拷贝成目标文件流,拷贝方法独立成为一个方法,方法的参数采用抽象流的形式。

//方法接受的参数类型尽量面向父类,越抽象越好,这样适应面更宽广。

}

分析listFiles方法内部的策略模式实现原理

File[] listFiles(FileFilter filter){

File[] files = listFiles();

//Arraylist acceptedFilesList = new ArrayList();

File[] acceptedFiles = new File[files.length];

int pos = 0;

for(File file: files){

boolean accepted = filter.accept(file);

if(accepted){

//acceptedFilesList.add(file);

acceptedFiles[pos++] = file;

}

}

Arrays.copyOf(acceptedFiles,pos);

//return (File[])accpetedFilesList.toArray();

}

26、编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串,但要保证汉字不被截取半个,如“我ABC”,4,应该截取“我AB”,输入“我ABCDEF”,6,应该输出“我ABC”,而不是“我ABC+汉的半个”。

答:

首先要了解中文字符有多种编码及各种编码的特征。

假设n为要截取的字节数。

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

String str = “我a爱中华abc def’;

String str = “我ABC汉”;

int num = trimGBK(str.getBytes(“GBK”),5);

System.out.println(str.substring(0,num) );

}

public static int  trimGBK(byte[] buf,int n){

int num = 0;

boolean bChineseFirstHalf = false;

for(int i=0;i

{

if(buf[i]<0 && !bChineseFirstHalf){

bChineseFirstHalf = true;

}else{

num++;

bChineseFirstHalf = false;

}

}

return num;

}

27、有一个字符串,其中包含中文字符、英文字符和数字字符,请统计和打印出各个字符的个数。

答:String content =“中国aadf的111萨bbb菲的zz萨菲”;

HashMap map = new HashMap();

for(int i=0;i

{

char c = content.charAt(i);

Integer num = map.get(c);

if(num == null)

num = 1;

else

num = num + 1;

map.put(c,num);

}

for(Map.EntrySet entry : map)

{

system.out.println(entry.getkey() +“:”+ entry.getValue());

}

如果一串字符如”aaaabbc中国1512″要分别统计英文字符的数量,中文字符的数量,和数字字符的数量,假设字符中没有中文字符、英文字符、数字字符之外的其他特殊字符。

int engishCount;

int chineseCount;

int digitCount;

for(int i=0;i

{

char ch = str.charAt(i);

if(ch>=’0’&& ch<=’9’)

{

digitCount++

}

else if((ch>=’a’&& ch<=’z’) || (ch>=’A’&& ch<=’Z’))

{

engishCount++;

}

else

{

chineseCount++;

}

}

System.out.println(……………);

28、从类似如下的文本文件中读取出所有的姓名,并打印出重复的姓名和重复的次数,并按重复次数排序:

1,张三,28

2,李四,35

3,张三,28

4,王五,35

5,张三,28

6,李四,35

7,赵六,28

8,田七,35

package com.huawei.interview;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.util.Comparator;

import java.util.HashMap;

import java.util.Iterator;

import java.util.Map;

import java.util.TreeSet;

public class GetNameTest {

/**

* @param args

*/

public static void main(String[] args) {

// TODO Auto-generated method stub

//InputStream ips = GetNameTest.class.getResourceAsStream(“/com/huawei/interview/info.txt”);

//用上一行注释的代码和下一行的代码都可以,因为info.txt与GetNameTest类在同一包下面,所以,可以用下面的相对路径形式

Map results = new HashMap();

InputStream ips = GetNameTest.class.getResourceAsStream(“info.txt”);

BufferedReader in = new BufferedReader(new InputStreamReader(ips));

String line = null;

try {

while((line=in.readLine())!=null)

{

dealLine(line,results);

}

sortResults(results);

}catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

static class User

{

public  String name;

public Integer value;

public User(String name,Integer value)

{

this.name = name;

this.value = value;

}

@Override

public boolean equals(Object obj) {

// TODO Auto-generated method stub

//下面的代码没有执行,说明往treeset中增加数据时,不会使用到equals方法。

boolean result = super.equals(obj);

System.out.println(result);

return result;

}

}

private static void sortResults(Map results) {

// TODO Auto-generated method stub

TreeSet sortedResults = new TreeSet(

new Comparator(){

public int compare(Object o1, Object o2) {

// TODO Auto-generated method stub

User user1 = (User)o1;

User user2 = (User)o2;

/*如果compareTo返回结果0,则认为两个对象相等,新的对象不会增加到集合中去

*所以,不能直接用下面的代码,否则,那些个数相同的其他姓名就打印不出来。

* */

//return user1.value-user2.value;

//return user1.value

if(user1.value

{

return -1;

}else if(user1.value>user2.value)

{

return 1;

}else

{

return user1.name.compareTo(user2.name);

}

}

}

);

Iterator iterator = results.keySet().iterator();

while(iterator.hasNext())

{

String name = (String)iterator.next();

Integer value = (Integer)results.get(name);

if(value > 1)

{

sortedResults.add(new User(name,value));

}

}

printResults(sortedResults);

}

private static void printResults(TreeSet sortedResults)

{

Iterator iterator  = sortedResults.iterator();

while(iterator.hasNext())

{

User user = (User)iterator.next();

System.out.println(user.name + “:” + user.value);

}

}

public static void dealLine(String line,Map map)

{

if(!””.equals(line.trim()))

{

String [] results = line.split(“,”);

if(results.length == 3)

{

String name = results[1];

Integer value = (Integer)map.get(name);

if(value == null) value = 0;

map.put(name,value + 1);

}

}

}

}

29、写一个Singleton出来。

第一种:饱汉模式

public class SingleTon {

private SingleTon(){

}

//实例化放在静态代码块里可提高程序的执行效率,但也可能更占用空间

private final static SingleTon instance = new SingleTon();

public static SingleTon getInstance(){

return instance;

}

}

第二种:饥汉模式

public class SingleTon {

private SingleTon(){}

private static instance = null;//new SingleTon();

public static synchronized SingleTon getInstance(){

if(instance == null)

instance = new SingleTon();

return instance;

}

}

第三种:用枚举

public enum SingleTon{

ONE;

}

第三:更实际的应用(在什么情况用单例)

public class SequenceGenerator{

//下面是该类自身的业务功能代码

private int count = 0;

public synchronized int getSequence(){

++count;

}

//下面是把该类变成单例的代码

private SequenceGenerator(){}

private final static instance = new SequenceGenerator();

public static SingleTon getInstance(){

return instance;

}

}

第四:

public class MemoryDao

{

private HashMap map = new HashMap();

public void add(Student stu1){

map.put(SequenceGenerator.getInstance().getSequence(),stu1);

}

//把MemoryDao变成单例

}

Singleton模式主要作用是保证在Java应用程序中,一个类Class只有一个实例存在。

一般Singleton模式通常有几种种形式:

第一种形式:定义一个类,它的构造函数为private的,它有一个static的private的该类变量,在类初始化时实例话,通过一个public的getInstance方法获取对它的引用,继而调用其中的方法。

public class Singleton {

private Singleton(){}

//在自己内部定义自己一个实例,是不是很奇怪?

//注意这是private只供内部调用

private static Singleton instance = new Singleton();

//这里提供了一个供外部访问本class的静态方法,可以直接访问

public static Singleton getInstance() {

return instance;

}

}

第二种形式:

public class Singleton {

private static Singleton instance = null;

public static synchronized Singleton getInstance() {

//这个方法比上面有所改进,不用每次都进行生成对象,只是第一次

//使用时生成实例,提高了效率!

if (instance==null)

instance=new Singleton();

return instance;

}

}

其他形式:

定义一个类,它的构造函数为private的,所有方法为static的。

一般认为第一种形式要更加安全些

30、一个整数,大于0,不用循环和本地变量,按照n2n4n8n的顺序递增,当值大于5000时,把值按照指定顺序输出来。

例:n=1237

则输出为:

1237,

2474,

4948,

9896,

9896,

4948,

2474,

1237,

提示:写程序时,先致谢按递增方式的代码,写好递增的以后,再增加考虑递减部分。

public static void doubleNum(int n)

{

System.out.println(n);

if(n<=5000)

doubleNum(n*2);

System.out.println(n);

}

Gaibaota(N) = Gaibaota(N-1) + n

31、1个人10,第2个比第1个人大2岁,依次递推,请用递归方式计算出第8个人多大?

package cn.demo;

import java.util.Date;

public class A1 {

public static void main(String [] args)

{

System.out.println(computeAge(8));

}

public static int computeAge(int n)

{

if(n==1) return 10;

returncomputeAge(n-1) + 2;

}

}

public static void toBinary(int n,StringBuffer result)

{

if(n/2 != 0)

toBinary(n/2,result);

result.append(n%2);

}

32、排序都有哪几种方法?请列举。用JAVA实现一个快速排序。

交换式排序、选择排序、插入排序、希尔排序、快速排序

public class QuickSort {

/**

*快速排序

* @param strDate

* @param left

* @param right

*/

public void quickSort(String[] strDate,int left,int right){

String middle,tempDate;

int i,j;

i=left;

j=right;

middle=strDate[(i+j)/2];

do{

while(strDate[i].compareTo(middle)<0&& i

i++; //找出左边比中间值大的数

while(strDate[j].compareTo(middle)>0&& j>left)

j–; //找出右边比中间值小的数

if(i<=j){ //将左边大的数和右边小的数进行替换

tempDate=strDate[i];

strDate[i]=strDate[j];

strDate[j]=tempDate;

i++;

j–;

}

}while(i<=j); //当两者交错时停止

if(i

quickSort(strDate,i,right);//从

}

if(j>left){

quickSort(strDate,left,j);

}

}

/**

* @param args

*/

public static void main(String[] args){

String[] strVoid=new String[]{“11″,”66″,”22″,”0″,”55″,”22″,”0″,”32”};

QuickSort sort=new QuickSort();

sort.quickSort(strVoid,0,strVoid.length-1);

for(int i=0;i

System.out.println(strVoid[i]+” “);

}

}

}

33、有数组a[n],用java代码将数组元素顺序颠倒

//用下面的也可以

//for(int i=0,int j=a.length-1;i

import java.util.Arrays;

public class SwapDemo{

public static void main(String[] args){

int [] a = new int[]{

(int)(Math.random() * 1000),

(int)(Math.random() * 1000),

(int)(Math.random() * 1000),

(int)(Math.random() * 1000),

(int)(Math.random() * 1000)

};

System.out.println(a);

System.out.println(Arrays.toString(a));

swap(a);

System.out.println(Arrays.toString(a));

}

public static void swap(int a[]){

int len = a.length;

for(int i=0;i

int tmp = a[i];

a[i] = a[len-1-i];

a[len-1-i] = tmp;

}

}

}

34、写一个方法,用一个for循环打印九九乘法表

/** *//**

*打印九九乘法口诀表

*/

public void nineNineMulitTable(){

for (int i = 1,j = 1; j <= 9; i++) {

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

if(i==j){

i=0;

j++;

System.out.println();

}

}

}

35、给定一个java.util.Date对象,如何转化为”2007-3-22 20:23:22”格式的字符串。【高达软件】

/** *//**

*将某个日期以固定格式转化成字符串

* @param date

* @return str

*/

public String date2FormatStr(Date date)

{

SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);

String str = sdf.format(date);

return str;

}

36、金额转换,阿拉伯数字的金额转换成中国传统的形式如:(¥1011)->(一千零一拾一元整)输出。

去零的代码:

return sb.reverse().toString().replaceAll(“零[拾佰仟]”,”零”).replaceAll(“零+万”,”万”).replaceAll(“零+元”,”元”).replaceAll(“零+”,”零”);

public class RenMingBi {

/**

* @param args add by zxx ,Nov 29, 2008

*/

private static final char[] data = new char[]{

‘零’,’壹’,’贰’,’叁’,’肆’,’伍’,’陆’,’柒’,’捌’,’玖’

};

private static final char[] units = new char[]{

‘元’,’拾’,’佰’,’仟’,’万’,’拾’,’佰’,’仟’,’亿’

};

public static void main(String[] args) {

// TODO Auto-generated method stub

System.out.println(

convert(135689123));

}

public static String convert(int money)

{

StringBuffer sbf = new StringBuffer();

int unit = 0;

while(money!=0)

{

sbf.insert(0,units[unit++]);

int number = money%10;

sbf.insert(0, data[number]);

money /= 10;

}

return sbf.toString();

}

}

37、写一个方法,能够判断任意一个整数是否素数

/** *//**

*判断任意一个整数是否素数

* @param num

* @return boolean

*/

public boolean isPrimeNumber(int num)

{

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

if(num%i==0)

{

return false;

}

}

return true;

}

38、123455个数字,用Java写一个Main函数,打印所有不同的排序

static int[] bits = new int[] { 1, 2, 3, 4, 5 };

/**

* @param args

*/

public static void main(String[] args) {

sort(“”, bits);

}

private static void sort(String prefix, int[] a) {

if (a.length == 1) {

System.out.println(prefix + a[0]);

}

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

sort(prefix + a[i], copy(a, i));

}

}

private static int[] copy(int[] a,int index){

int[] b = new int[a.length-1];

System.arraycopy(a, 0, b, 0, index);

System.arraycopy(a, index+1, b, index, a.length-index-1);

return b;

}

39、写一个方法,输入任意一个整数,返回它的阶乘

/** *//**

*获得任意一个整数的阶乘

n

!

*/

public int factorial(int num)

{

//递归

if(num == 1)

{

return 1;

}

return num*factorial(num-1);

}

40、写一个方法,用二分查找法判断任意整数在任意整数数组里面是否存在,若存在就返回它在数组中的索引位置,不存在返回-1

/** *//**

*二分查找特定整数在整型数组中的位置(递归)

dataset

data

beginIndex

endIndex

index

*/

public int binarySearch(int[] dataset,int data,int beginIndex,int endIndex){

int midIndex = (beginIndex+endIndex)/2;

//如果查找的数要比开始索引的数据要小或者是比结束索引的书要大,或者开始查找的索引值大于结束的索引值返回-1没有查到

if(data dataset[endIndex]||beginIndex>endIndex){

return -1;

}

if(data 

return binarySearch(dataset,data,beginIndex,midIndex-1);

}else if(data>dataset[midIndex])

{

return binarySearch(dataset,data,midIndex+1,endIndex);

}else {

return midIndex;

}

}

/** *//**

*二分查找特定整数在整型数组中的位置(非递归)

dataset

data

index

*/

public int binarySearch(int[] dataset ,int data)

{

int beginIndex = 0;

int endIndex = dataset.length – 1;

int midIndex = -1;

if(data dataset[endIndex]||beginIndex>endIndex){

return -1;

}

while(beginIndex <= endIndex) {

midIndex = (beginIndex+endIndex)/2;

if(data 

endIndex = midIndex-1;

} else if(data>dataset[midIndex]) {

beginIndex = midIndex+1;

}else {

return midIndex;

}

}

return -1;

}

41、如果一个序列的前四个数字分别是2,9,28,65请问第五个数字是?

1³+1=2

2³+1=9

3²+1=28

4³+1=65

所以继续的话应是

5³+1=126

42、编写函数找出11000之内能被3整除且不是偶数的整数,并按个位数的大小从大到小排序

public List find() {

List list=new ArrayList();

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

if (i%3==0 && i%2!=0) {

list.add(i);

}

}

return list;

}

43、java方法编写计算指定目录下所有文件占空间大小

//返回文件大小private void getFileSize()throws RuntimeException,IOException

{//初始化文件大小为0;

this.longSize=0;

//如果文件存在而且是文件,直接返回文件大小

if(file.exists()&&file.isFile()){

this.longSize= file.length();

}

//文件存在而且是目录,递归遍历文件目录计算文件大小else if(file.exists()&&file.isDirectory()){

getFileSize(file);//递归遍历

}else{

throw new RuntimeException(“指定文件不存在”);

}

}

44、一个list中,有b.a.b.c.b.b.写个方法去掉所有b

public List qub(List list) {

List alist=new ArrayList();

for (int i = 0; i < list.size(); i++) {

String a=(String)list.get(i);

if (!a.equals(“b”)) {

alist.add(a);

}

}

return alist;

}

45、设计线程的生产者和消费者模式

package com;

import java.io.*;

import java.util.*;

public class Test1 {

Vector v = new Vector();

int index = -1;

boolean isput = false;

public synchronized void put(String name) throws InterruptedException{

if(isput){

wait();

}

v.add(name);

index++;

isput = true;

notify();

System.out.println(Thread.currentThread().getName());

}

public synchronized  void get() throws InterruptedException{

if(!isput){

wait();

}

System.out.println(Thread.currentThread().getName()+”取:”+v.get(index));

isput = false;

notify();

}

public static void main(String[] args) throws CloneNotSupportedException, FileNotFoundException, IOException, InterruptedException {

Test1 t = new Test1();

A a = new A(t);

B b = new B(t);

new Thread(a).start();

new Thread(b).start();

}

}

class A implements Runnable{

Test1 t;

public A(Test1 t){

this.t = t;

}

@Override

public void run() {

int i  =0 ;

while(true){

if(i==0){

try {

t.put(“男”);

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}else{

try {

t.put(“女”);

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

i = (i+1)%2;

}

}

}

class B implements Runnable{

Test1 t;

public B(Test1 t){

this.t = t;

}

@Override

public void run() {

// TODO Auto-generated method stub

while(true){

try {

t.get();

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

}

46、写一个方法求两个数的公约数

importjava.util.ArrayList;

importjava.util.List;

publicclassMaxNum {

intnum=0;

publicListMaxs(inta){//先找出能被第一个数整除的数

List list=newArrayList();

for(inti = 1; i <= a; i++) {

if(a%i==0){

list.add(i);

}

}

returnlist;

}

publicvoidTest(inta,intb){

List list=newMaxNum().Maxs(a);

for(inti = 0; i < list.size(); i++) {

intbb=(Integer) list.get(i);

if(b%bb==0){//找出能被第二个数整出并且也能被第二个数整除的数

num=bb;

}

}

System.out.println(“最大公约数为:”+num);

}

publicstaticvoidmain(String[] args) {

newMaxNum().Test(100,1000);

}

}

47、实现字符串的反转。如:abcd输出dcba

答:

StringBufferstringBuffer =

newStringBuffer().append(“abc”).reverse();

System.out.println(stringBuffer.toString());

48、编写程序将由数字及字符组成的字符串中的数字截取出来并按顺序输出,例如:ABC137GMNQQ2049PN5FFF”输出结果应该为01234579

package com.tarena;

import java.util.Arrays;

public class NumberSplitChar {

public static void main(String[] args) {

String str=”ABC137GMNQQ2049PN5FFF”;

char[] beforechars=str.toCharArray();

char[] afterchars=new char[beforechars.length];

int j=0;

for(int i=0;i

if(beforechars[i]>=’0′ && beforechars[i]<=’9′){

afterchars[j++]=beforechars[i];

}

}

Arrays.sort(afterchars);

for(int i=(afterchars.length-j);i

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

}

}

}

下载完整面试题文件:

java面试题大全

    原文作者:独云
    原文地址: https://www.jianshu.com/p/9f8b564ed562
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞