input, array

import java.io.Console;
import java.util.*;

public class Test{
    public static void main(String[] args) {
//         get user's input (including blankspace)
        Scanner in = new Scanner(System.in);
        System.out.println("Your name?");
        String name = in.nextLine();
        System.out.println(name);
        
        System.out.println("again");
        String name_not_include_space = in.next();
        System.out.println(name_not_include_space);
        
        // get int
        System.out.println("Your age?");
        int age = in.nextInt();
        System.out.println(age);
        
    }
}

 array

import java.io.Console;
import java.util.*;

public class Test{
    public static void main(String[] args) {
        // define an array
        int[] a = new int[10];
        // for each 
        for(int i = 0; i <= a.length - 1; i++)
            a[i] = i;
        for(int ai: a) {
            System.out.println(ai);
        }
        // get user friendly array content
        System.out.println(Arrays.toString(a));
        
        // another way to create an array
        int[] an = {3,4,5,1};
        System.out.println(Arrays.toString(an));
        
        // 数组长度可以为0, 和null不同
        int[] a0 = new int[0];
        System.out.println(Arrays.toString(a0));
        
        // 数组浅拷贝
        int[] an_ = an;
        an_[0] = 100;
        System.out.println(Arrays.toString(an));
        
        // 数组深拷贝, 外加延长length,0填充,长度也可小于原始长度
        // copyOfRange 同理
        int[] an__ = Arrays.copyOf(an, an.length * 2);
        an__[0] = 888;
        System.out.println(Arrays.toString(an__));
        System.out.println(Arrays.toString(an));
        
        // 也可对args进行操作
        // java Test -g c w => 0: g, 1: c, 2:w
        
        //sort
        // System.out.println();
        Arrays.sort(an);
        System.out.println(Arrays.toString(an));
        
        // 二维数组
        int[][] db = new int[3][5];
        //or:
        int[][] dbs= {
                {1,2},
                {3,4},
                {5,6}
        };
        // traverse:
        for(int[] k: dbs) {
            for(int kk: k)
                System.out.print(kk + "*");
        }
        System.out.println();
        // or:
        System.out.println(Arrays.deepToString(dbs));
        
        // 不规则数组
        int[][] odds = new int[5][];
        for(int ii = 0; ii <= 5-1; ii++)
            odds[ii] = new int[ii+1];
    }
}

 

posted @ 2018-11-26 09:54  geeklove  阅读(279)  评论(0编辑  收藏  举报