Java代码和编程题


黑夜给了我黑色眼睛 我却用它去寻找光明 ——顾城


1 Switch语句-百分制分数到等级分数

public class SwitchTest {
    public static void main(String args[]){
        test(57);
    }
    private static void  test(int i){
        int s =(i/10);
        switch(s){
        case 9: System.out.println("A"); 
        break;
        case 8: System.out.println("B"); 
        break;
        case 7: System.out.println("C"); 
        break;
        case 6: System.out.println("D"); 
        break;
        default :System.out.println("E");
        break;
        }
    }
}

2 For循环 乘法口诀表

public class ForTest {

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

3 排序

输入n个整数,输出最大值

import java.util.Scanner;

public class MaxTest2 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int min = 0;
        int max = 0;
        int[] b = new int[n];
        for (int i = 0; i < n; i++) {
            b[i] = sc.nextInt();
        }

        min = max = b[0];
        for (int i = 1; i < n; i++) {
            if (min > b[i]) {
                min = b[i];
            }
            if (max < b[i]) {
                max = b[i];
            }
        }
        System.out.println(min + " " + max);
    }
}

输出3个整数中的最大值

public class MaxTest {
    public static void main(String[] args) {
        maxtest(33,5,63);
    }
    private static void maxtest(int a,int b,int c) {
        //a = a>b?a:b;
        //a = a>c?a:c;
        a = a>b?(a>c?a:c):(b>c?b:c);
        System.out.println("Max:"+a);
    }
}

4 抽象类

public abstract class Abstract {
    //普通变量
    @SuppressWarnings("unused")
    private String name;

    public String pwd;//变量
    public  final int i = 1;//常量
    public static int j;//静态变量
    public static final int y =3;//静态常量,全局常量

    //抽象方法
    public  abstract boolean isup(String name);
    //普通方法
    @SuppressWarnings("unused")
    private void test(){};

    public void test2(){};

    public static void test3(){};

}   

抽象只针对方法,抽象类的变量和普通类的变量一样

5 输出棋盘图案

public class Tuan {
    public static void main(String[] args) {
        int SIZE = 19;
        for (int i = 0; i < SIZE; i++) {
            if (i < 10) {
                System.out.print("  " + i);// 两个空格
            } else {
                System.out.print("  " + (char) (i - 10+ 'a' ));// 两个空格
            }
        }
        System.out.println();
        // System.out.print(i<10?(char)(i+'0'):(char)(i+'a'-10));
        for (int i = 0; i < SIZE; i++) {
            if (i < 10) {
                System.out.print(i + " ");// 一个空格
            } else {
                System.out.print((char) (i - 10+ 'a' ) + " ");// 一个空格
            }
            for (int j = 0; j < SIZE; j++) {
                System.out.print("*" + "  ");// 两个空格
            }
            System.out.println();
        }
    }
}
  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f  g  h  i
0 *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  
1 *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  
2 *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  
3 *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  
4 *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  
5 *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  
6 *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  
7 *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  
8 *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  
9 *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  
a *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  
b *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  
c *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  
d *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  
e *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  
f *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  
g *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  
h *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  
i *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  

6 一个数倒序排列

public class Daoxu {
    public static void main(String[] args) {
        int olddata = 3758;
        int newdata = 0;
        while (olddata != 0) {
            for (int i = 0; i < 4; i++) {//针对4位数,5位就循环五次
                newdata = newdata * 10 + olddata % 10;//对于一个数用10求余得到末位数
                olddata = olddata / 10;//除10,依次向前
                //newdata的数据依次为 8 85 857 8573
            }
            System.out.println("newdata=" + newdata);
        }
    }
}

7 字符串的倒序排列

/**
 * Title: Test16114d
 * Description: 一个字符串倒序排列
 * @author Peng
 * @date 上午11:33:17
 */
public class Test16114d2 {
    public static void main(String[] args) {
        convertStr2("honey");
    }
    private static void convertStr(String string) {
        //StringBuffer的reverse方法实现反转
        String str = new StringBuffer(string).reverse().toString();
        System.out.println(str);        
    }

    private static void convertStr2(String string) {
        for(int i=string.length()-1;i>=0;i--){
            System.out.print(string.charAt(i));
        }   
    }
}

8 判断素数(质数)

质数(prime number)又称素数,有无限个。质数定义为在大于1的自然数中,除了1和它本身以外不再有其他因数的数称为质数。

在一般领域,对正整数n,如果用2到根号n之间的所有整数去除,均无法整除,则n为质数。
质数大于等于2 不能被它本身和1以外的数整除

/**
 * Title: Test16114c
 * Description: 判断一个数是否为素数
 * @author Peng
 * @date 上午11:19:41
 */
public class Test16114c {
    public static void main(String[] args) {
        test(2);
    }

    private static void test(int number) {
        int i;
        boolean istrue = true;
        for(i=2;i<=Math.sqrt(number);i++){
            if(number%i==0)
                istrue =false;              
        }
        if(istrue){
            System.out.println(number+"是素数");
        }else{
            System.out.println(number+"不是素数");
        }
    }
}

输出2-100间的素数

/**
 * 
 * Title: Test16114c2
 * Description: 输出2到100间的素数
 * @author Peng
 * @date 上午11:17:44
 */
public class Test16114c2 {
    public static void main(String[] args) {
        for(int i=2;i<100;i++){
            test(i);
        }

    }
    private static void test(int number) {
        int i;
        boolean istrue = true;
        for(i=2;i<=Math.sqrt(number);i++){
            if(number%i==0)
                istrue =false;              
        }
        if(istrue){
            System.out.print(number+" ");
        }
    }
}

9数字的二进制排列

/**
 * Title: Test16114e
 * Description: 数字的二进制输出
 * @author Peng
 * @date 下午4:45:28
 */
public class Test16114e {

    public static void main(String[] args){
        int n;
        Scanner s=new Scanner(System.in);
        System.out.println("please input a number:");
        n=s.nextInt();
        //23232
        //00000000 00000000 01011010 11000000 
        for(int i=31;i>=0;i--){
            // 1左移i位,后面补i个零 
            // 1左移9位 10000000 00
            if((n&(1<<i))!=0){//按位与 左移  先从32位开始匹配,依次向下匹配,就是判断这位是不是1
                System.out.print("1");
            }else{
                System.out.print("0");
            }
            if((32-i)%8==0){//4可以按0000 0000 间隔
                System.out.print(" ");
            }
        }

    }
}  

11 数组分隔、排序

package com.test.c;

import java.util.*;

public class Test118 {
    public static String[] splitStringByComma(String source) {
        if (source == null || source.trim().equals(""))
            return null;
        //StringTokenizer分解字符串,StringTokenizer(String s)
        //默认的分隔标记 空格、换行符、回车符、tab键、进纸符做分隔标记、
        //StringTokenizer(source, ", ; ()")
        StringTokenizer commaToker = new StringTokenizer(source, ",");
        String[] result = new String[commaToker.countTokens()];
        int i = 0;
        while (commaToker.hasMoreTokens()) {
            result[i] = commaToker.nextToken();
            i++;
        }
        return result;
    }

    public static void main(String args[]) {
        String[] s = splitStringByComma("5,8,7,4,3,9,1");
        int[] ii = new int[s.length];
        for (int i = 0; i < s.length; i++) {
            ii[i] = Integer.parseInt(s[i]);
        }
        Arrays.sort(ii);
        // asc升序
        for (int i = 0; i < s.length; i++) {
            System.out.println(ii[i]);
        }
        // desc降序
        for (int i = (s.length - 1); i >= 0; i--) {
            System.out.println(ii[i]);
        }
    }
}

12 利用 IO 流复制一个文件到另一个文件中

输入流用 read 方法读取源中的数据
输出流用 write 方法流中写书数据
http://blog.csdn.net/peng_hong_fu/article/details/52605935

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class MyTestIO {
    public static void main(String[] args) {
        try {
            FileInputStream in = new FileInputStream("FileStream2.java");
            File f = new File("peng.txt");
            FileOutputStream out = new FileOutputStream(f);
            byte [] buffer = new byte[1024];
            int n = -1;
            while((n=in.read(buffer))!=-1){
                String s =new String(buffer,0,n);
                System.out.println(s);
                out.write(buffer);
            }
            out.close();
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

13 模式匹配

编写java程序,提示用户输入一个保险号码,格式为DDD-DD-DDDDD为一个数字。检查是否匹配。

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Mytest {
    public static void main(String[] args) {

        String regex = "[0-9]{3}-[0-9]{2}-[0-9]{5}";
        Pattern p = Pattern.compile(regex);
        //String test = "232-23-33333";    
        System.out.println("请输入匹配的字符:");
        Scanner in = new Scanner(System.in); 
        while(in.hasNext()){
            String test1 = in.nextLine();
             Matcher m = p.matcher(test1);
            boolean dataFlag = m.matches();
            if (!dataFlag) {
                System.out.println("格式错误");
            }else{
                System.out.println("格式正确");
            }
           System.out.println("再次输入匹配的字符:");
        }   
    }   
}

14 代码查错

1

public class Test118 {

    void doSomething() {
        private String s = "";
        int l = s.length();
    }

}

错。局部变量前不能放置任何访问修饰符 (private,public,和protected)。final可以用来修饰局部变量
(final如同abstract和strictfp,都是非访问修饰符,strictfp只能修饰class和method而非variable)。

strictfp, 即 strict float point (精确浮点)。
strictfp 关键字可应用于类、接口或方法。使用 strictfp 关键字声明一个方法时,该方法中所有的float和double表达式都严格遵守FP-strict的限制,符合IEEE-754规范。当对一个类或接口使用 strictfp 关键字时,该类中的所有代码,包括嵌套类型中的初始设定值和代码,都将严格地进行计算。严格约束意味着所有表达式的结果都必须是 IEEE 754 算法对操作数预期的结果,以单精度和双精度格式表示。
如果你想让你的浮点运算更加精确,而且不会因为不同的硬件平台所执行的结果不一致的话,可以用关键字strictfp.

2

public class Something {
    public int addOne(final int x) {
        return ++x;
    }
}

错。int x被修饰成final,意味着x不能在addOne method中被修改。

3

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并没有改变。

4

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。

5

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;”。

6


interface A {
    static final 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();
    }
}

The field x is ambiguous模棱两可,不明确

答案:错误。在编译时会发生错误(错误描述不同的JVM有不同的信息,意思就是未明确的x调用,两个x都匹配(就象在同时import java.util和java.sql两个包时直接声明Date一样)。对于父类的变量,可以用super.x来明确,而接口的属性默认隐含为 public static final.所以可以通过A.x来明确。

7

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”);”这里显示有错。

15 用JAVA写一个多线程程序,写四个线程…

/**
 * 用JAVA写一个多线程程序,写四个线程,其中二个对一个变量加1,另外二个对一个变量减1
 * 
 * 1、线程同步--synchronized
 * 2、线程之间如何共享同一个count变量--内部类
 * Created by Peng
 * Time: 2017/6/7 22:59
 */
public class TestThread {
    private int count = 100;

    public static void main(String[] args) {

        TestThread testThread = new TestThread();
        TestThread1 testThread1 = testThread.new TestThread1();
        TestThread2 testThread2 = testThread.new TestThread2();

        for (int i = 0; i < 2; i++) {
            Thread thread = new Thread(testThread1);
            thread.start();
            thread = new Thread(testThread2);
            thread.start();
        }
    }

    private synchronized void dec() {
        for (int i = 0; i < 10; i++) {
            count--;
            System.out.println("减count:" + count);
        }
    }

    private synchronized void add() {
        for (int i = 0; i < 10; i++) {
            count++;
            System.out.println("加count:" + count);
        }
    }

    public class TestThread1 implements Runnable {
        @Override
        public void run() {
            dec();
        }
    }

    public class TestThread2 implements Runnable {
        @Override
        public void run() {
            add();
        }
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值