2016-04-05 91 views
0

有//告訴我需要幫助。所以我採取了用戶輸入,現在我試圖用另一種方法打印輸入。我的數組的內容必須打印出來。對象和類。如何使用for循環打印用戶輸入?

import java.util.Scanner; 

public class Running_Calcs { 

public static void main(String[] args) { 
    Scanner kbd = new Scanner(System.in); 

    final int MAX_RUNNERS = 4; 
    banner(); 
    Runner[] ar = new Runner[MAX_RUNNERS]; 
// This is an array for user input. Getter and setter are already set for name,distance,time. 
    for (int i = 0; i < ar.length; i++) { 
     System.out.println("\nInformation for runner 1/3"); 
     System.out.print("Name: "); 
     String name = kbd.next(); 
     System.out.print("Miles: "); 
     double distance = kbd.nextDouble(); 
     System.out.print("Minutes: "); 
     int time = kbd.nextInt(); 
    } 

    kbd.close(); 
} 

public static void printRunners(Runner[] ar) { 
    for (int i = 0; i < ar.length; i++) { 
     System.out.println("First Print of runners"); 
     System.out.println("-----------------------"); 
     System.out.println(ar[i]); 
    } 
    banner(); 

} 
// I am trying to print the info from the array in this method. I don't know how. 
//Along with that , I am trying to print the pace and Temp which I already have in my other class. 
private static void banner() { 
    System.out.println("---------------------------"); 
    System.out.println("Track runner info and pace\nGustavo Bruno"); 
    System.out.println("---------------------------"); 
} 

} 
+0

如果你有getters和setter,你爲什麼不使用它們? –

+0

我必須在PrintRunners方法中調用它們嗎? –

+0

您必須在循環的每次迭代中實例化一個新的runner,使用您擁有的setter方法設置其屬性,並將該實例存儲在數組中。在printRunners方法中,你必須爲每個跑步者調用相應的getter方法。 – RubioRic

回答

0

我建議重寫類轉輪

ToString方法並調用它在該方法中printRunners

public static void printRunners(Runner[] ar) { 
    for (int i = 0; i < ar.length; i++) { 
     System.out.println("First Print of runners"); 
     System.out.println("-----------------------"); 
     System.out.println(ar[i].toString()); //here!!! 
    } 
    banner(); 

} 
+0

它在我的第一個for循環結束後停止打印信息;在它到達printsRunners方法之前。 –

+0

有什麼錯誤?在問題中發佈該信息 –

0

主要()方法定義內的名爲「AR」可變方法。該值不能在方法外訪問。爲了訪問它,你需要將其申報爲類的靜態變量:

private static Runner[] ar; 

當打印了這一點,你需要遍歷它:

for(Runner r : ar){ 
    // somehow print out the Runner class (you haven't included this) 
    System.out(r.getName() + "\t" + r.getDistance() + "\t" + r.getTime(); 
} 

如果你的亞軍現在

,您遇到的另一個問題是沒有調用printRunners()方法。我假設你想在main()方法的結尾調用它?