繁体   English   中英

将两个1d阵列组合成一个二维阵列?

[英]combining two 1d arrays into a 2d array?

我试图让这个程序打印出来。

Smith     1000
doe       1200
john      1400
bailey    900
potter    1600

程序本身需要数组我需要找到一种可能组合两个1d数组的方法,或者只是一种正确格式化的方式,以便以上述方式打印出来。

该程序:

import java.util.*;
public class TwoArrays {

    static Scanner console = new Scanner(System.in);

    public static void main(String[]args){
        String [] name = new String[5];
        int [] vote = new int[5];

        String lastname;
        int votecount;
        int i;

        for(i=0; i<name.length; i++){
            System.out.println("Enter the last name of the candidate: ");
            lastname = console.next();
            name[i]= lastname;
            System.out.println("Enter the number of votes the candidate got: ");
            votecount = console.nextInt();
            vote[i] = votecount;
        }

        String printing = Print(name);
        int printing2 = Print2(vote);

    }

    public static String Print(String [] pname){

        for (int i=0; i<pname.length; i++){
                System.out.println(pname[i]+ "      \n");
        }
        return "nothing";

    }
    public static int Print2(int [] pvote){
        for (int i=0; i<pvote.length; i++){
                System.out.println(pvote[i]+ "      \n");
        }
        return 0;
    }
}

为此,您需要使用System.out.printf设置合理的空间。 在这里,我将%-15s用于左对齐。 您可以轻松地从pname大小计算它。

 public static void print(String[] pname, int[] pvote) {
    for (int i = 0; i < pname.length; i++) {
        System.out.printf("%-15s   %d\n", pname[i], pvote[i]);
    }
}

“只是一种正确格式化的方式,所以它以上述方式打印出来。”:

 public static void Print(String [] pname, int [] votes){

        for (int i=0; i<pname.length; i++){
                System.out.printf("%-10s %5d\n", pname[i], votes[i]);
        }
    }

然后显然只调用一次,两个数组作为参数:

Print(name, vote);

(与最新的编辑,你会得到一些不错的序列上的名称在10场左对齐,数量,宽度5的场右对齐您可以在两者之间添加其他字符(例如: )只凭将其插入格式字符串。)

for (int i=0;i<pname.length;i++) {
    System.out.println(pname[i]+ "      "+pvote[i]);
}

将其添加为实例变量:

HashMap<String, Integer> candidateMap = new HashMap<String, Integer>();

然后在你的循环中:

System.out.println("Enter the last name of the candidate: ");
lastname = console.next();      
System.out.println("Enter the number of votes the candidate got: ");
votecount = console.nextInt();
candidateMap = candidateMap.put(lastname, votecount);

然后你的打印方法(信用@Masud正确的打印格式):

public static void Print(){
    for (String candidate : candidateMap.keySet()){
            System.out.printf("%-15s   %d\n", candidate, candidateMap.get(candidate));
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM