2013-12-10 166 views
0

我想盡可能地把這個程序打印出來。將兩個1d數組合併成一個二維數組?

Smith  1000 
doe  1200 
john  1400 
bailey 900 
potter 1600 

程序本身具有陣列我要麼需要找出可能結合兩個一維數組或只是一種方式,以便它在上面的方式打印出正確格式化的方式。

方案:

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; 
    } 
} 
+2

使用哈希映射,其中名稱是關鍵,和票是價值 – turbo

回答

2

爲此你需要設置使用合理的空間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]); 
    } 
} 
0

「只是一種正確的格式化它,所以它上面的方式打印出來。」:

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場右對齊您只需將其插入格式字符串之間(例如:)添加其它字符。)

+0

我試過這一點,它不能正常工作首先,如果它是一個虛空返回不能在那裏,當我去打電話'打印(名稱,投票)'沒有結束打印 – Bailey507

+0

對不起 - 你的評論被截斷了。你得到的錯誤是什麼?我認爲沒有任何東西的「返回」是有效的,因爲'void'函數的結束......這看起來與@ Masud的代碼非常相似 - 是不是也適合你? – Floris

+0

這只是扔掉東西的回報。 – Bailey507

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

我寧願使用選項卡,以便按照示例中的要求對齊數字。或者在固定寬度的字段中輸出名稱。 – Floris

+0

是的,這將是更加整潔。我只使用固定寬度,因爲這是現有代碼中的內容。 –

0

添加爲一個實例變量:

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)); 
    } 
} 
+0

標籤'\ t'不能正確顯示各種字長。 – Masudul

+0

@Masud你是對的。希望你不介意我是否用適當的信用來回答你的答案。 – turbo

相關問題