Java 将两个一维阵列合并为二维阵列?
我正在尝试可能得到这个程序打印出来作为Java 将两个一维阵列合并为二维阵列?,java,multidimensional-array,formatting,Java,Multidimensional Array,Formatting,我正在尝试可能得到这个程序打印出来作为 Smith 1000 doe 1200 john 1400 bailey 900 potter 1600 程序本身需要数组,我需要找到一种可能组合两个1d数组的方法,或者只是一种正确格式化它的方法,这样它就可以按照上面的方式打印出来 该方案: import java.util.*; public class TwoArrays { static Scanner console = new Scanner
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;
}
}
import java.util.*;
公共类数组{
静态扫描仪控制台=新扫描仪(System.in);
公共静态void main(字符串[]args){
字符串[]名称=新字符串[5];
整数[]投票=新整数[5];
字符串lastname;
int votecount;
int i;
对于(i=0;i“只是一种正确格式化的方法,以便以上述方式打印出来。”:
(使用最新的编辑,您可以获得一些很好的对齐方式。名称在10的字段中左对齐,数字在5的宽度字段中右对齐。您可以通过将其插入格式字符串中,在两者之间添加其他字符(例如,:
)(inti=0;i为此,您需要使用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]);
}
}
公共静态无效打印(字符串[]pname,int[]pvote){
对于(int i=0;i
将其添加为实例变量:
HashMap<String, Integer> candidateMap = new HashMap<String, Integer>();
然后,您的打印方法(正确的打印格式归功于@Masud):
使用哈希映射,其中名称是键,投票是值。我更喜欢使用制表符,以便数字按照示例中的要求对齐。或者在固定宽度字段中打印名称。是的,这样会更整洁。我只使用固定宽度,因为这是现有代码中的内容。制表符\t
无法正确显示各种单词length.@Masud你是对的。希望你不介意我在你的答案中使用你的答案,并给予适当的信任。我尝试过这个方法,但它没有正确地工作,如果它是无效的,回报不能在那里,当我去调用“打印(姓名,投票)”时'没有任何结果打印出来令人担忧-您的评论被截断。您得到的错误是什么?我认为return
with nothing作为void
函数的结尾是有效的…这看起来非常类似于@Masud的代码-这对您也不起作用吗?只是返回造成了一些问题。
for (int i=0;i<pname.length;i++) {
System.out.println(pname[i]+ " "+pvote[i]);
}
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]);
}
}
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);
public static void Print(){
for (String candidate : candidateMap.keySet()){
System.out.printf("%-15s %d\n", candidate, candidateMap.get(candidate));
}
}