2011-10-06 56 views
-2

我需要從文件中讀取一些數組並打印它們。我的第一個課程處理菜單驅動的程序,用戶輸入一個數字來告訴程序連接到文件,打印文件中的名稱,整數,字符或雙打。我堅持的第一件事是連接到文件。這是我的不完整的類從文件讀取:在java中打印一個列表

import java.util.*; 
public class Prog5Methods{ 
public Prog5Methods(){ 
} 
    public void ReadFromFile(Scanner input, String [] names, int [] numbers, char [] letters, double [] num2){ 
     System.out.println("\nReading from a file...\n"); 
     System.out.println("\nDONE\n"); 
     int r = 0; 
      while(input.hasNext()){ 
       names[r] = input.next(); 
       numbers[r] = input.nextInt(); 
       letters[r] = input.next().charAt(0); 
       num2[r] = input.nextDouble(); 
       r++; 
     } 
} // end of readFromFile 




} 

這是我從讀文件包含:

Lee Keith Austin Kacie Jason Sherri  Jordan  Corey Reginald Brian Taray 
Christopher Randy Henry Jeremy Robert Joshua Robert Eileen 
Cassandra Albert Russell Ethan Cameron Tyler Alex Kentrell rederic 
10 20 100 80 25 35 15 10 45 55 200 300 110 120 111 7 27 97 17 37 
21 91 81 71 16 23 33 45 
A b c w e r t q I u y b G J K S A p o m b v x K F s q w 
11.5 29.9 100 200 115.1 33.3 44.4 99.9 100.75 12.2 13.1 20.3 55.5 77.7 
12.1 7.1 8.2 9.9 100.1 22.2 66.6 9.9 1.25  3.75 19.9 3.321 45.54 88.8 

的名字是數組名[],該整數是在陣列數字[]等。我需要從這些數組中打印每個變量。

+0

您可以使用適當的['Arrays.toString()'] (http://download.oracle.com/javase/7/docs/api/java/util/Arrays.html)? – trashgod

+0

目前還不清楚,文件格式是什麼。文本文件不包含數組。名稱之間,整數之間是否真的有換行符?你事先知道名字的數量嗎?你是否被迫使用數組 - 因爲它會更復雜,(讀兩次文件),如果你使用數組並且不知道元素的數量。 –

回答

0

使用List<T>代替陣列。從基礎流使用掃描儀

public static void ReadFromFile(Scanner input, 
     ArrayList<String> names, 
     ArrayList<Integer> numbers, 
     ArrayList<Character> letters, 
     ArrayList<Double> num2) 
{ 

    while(input.hasNext()) 
    { 
    String val=input.next(); 
    Object no=parseInt(val); 
    if(no!=null) //Is integer? 
     { 
      numbers.add((Integer)no); 
     } 
    else 
    { 
     no=parseDouble(val); 
     if(no!=null) // Is double? 
     { 
      num2.add((Double)no); 
      } 
     else 
     { 
      no=parseChar(val); 
      if(no!=null) //Is Char? 
      { 
      letters.add((Character)no); 
      } 
      else 
      { 
       names.add(val); // String 
      } 
     } 
     } 
    } 
} 

方法解析字符串

讀取值。

public static Integer parseInt(String str) 
    { 
     Integer retVal=-1; 
     try 
     { 
      retVal=Integer.parseInt(str); 
     }catch(Exception ex) { return null;} 
     return retVal; 
    } 
    public static Double parseDouble(String str) 
    { 
     double retVal=-1; 
     try 
     { 
      retVal=Double.parseDouble(str); 
     }catch(Exception ex) { return null;} 
     return retVal; 
    } 
    public static Character parseChar(String str) 
    { 
     Character retVal=null; 

     if(str.length()==1) 
      retVal=str.charAt(0); 
     return retVal; 
    } 

測試你的代碼

public static void main(String[] args) throws Exception 
     { 
     ....... 
     ArrayList<String> names=new ArrayList<String>(); 
     ArrayList<Integer> numbers=new ArrayList<Integer>(); 
     ArrayList<Double> num2=new ArrayList<Double>(); 
     ArrayList<Character> letters=new ArrayList<Character>(); 

     ReadFromFile(input,names,numbers,letters,num2); 

     System.out.println(names); 
     System.out.println(numbers); 
     System.out.println(letters); 
     System.out.println(num2); 
     } 
0

對於從文本文件中讀取數據,FileReader是您的最佳選擇;

BufferedReader b = new BufferedReader(new FileReader("filename.txt")); 
String s = ""; 
while((s = b.readLine()) != null) { 
    System.out.println(s); 
} 

會讀取文件中的每一行,並一次將其打印到標準輸出一行。

import java.io.*; 
public class Prog5 { 
    public static String names[]; 
    public static int integers[]; 
    public static char letters[]; 
    public static float decimals[]; 
    public void readFileContents() { 
     File f = new File("yourfilename.txt"); 
     byte b = new byte[f.length()]; 
     FileInputStream in = new FileInputStream(f); 
     f.read(b); 
     String wholeFile = new String(b); 
     String dataArray[] = wholeFile.split(" "); 
     for(int i = 0; i < dataArray.length; i++) { 
     String element = dataArray[i]; 
     //in here you need to figure out what type element is 
     //or you could just count a certain number or each type if you know in advance 
     //then you need to parse it with eg Integer.parseInt(element); for the integers 
     //and put it into the static arrays 
     } 
    } 
} 
+0

感謝您的回答,這將工作,但我需要每個類型的變量在一個數組(他們已經是),我需要從不同的數組中打印每個變量。 – Josh

+0

@Josh - 文件的內容是什麼?是csv還是別的? – adatapost

+0

該文件是一個.txt文件。我將編輯我的當前代碼 – Josh

0

您需要周圍的文件名 '新文件',創建一個掃描儀,

p5m.readFromFile (new Scanner (new File("user.data")), 

要使用它,你需要java.io:

import java.io.*; 

如果我堅持您的要求,使用數組,和掃描儀,我可以做這樣的事情:

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

public class Prog5Methods 
{ 
    public void readFromFile (Scanner input, String [] names, int [] numbers, char [] letters, double [] num2) 
    { 
     System.out.println("\nReading from a file...\n"); 
     String [][] elems = new String [5][]; 
     for (int i = 0; i < 4; ++i) 
     { 
      elems[i] = input.nextLine().split ("[ \t]+"); 
     } 

     for (int typ = 0; typ < 4; ++typ) 
     { 
      int i = 0; 
      for (String s: elems[typ]) 
      { 
       switch (typ) 
       { 
        case 0: names [i++] = s; break; 
        case 1: numbers[i++] = Integer.parseInt (s); break; 
        case 2: letters[i++] = s.charAt (0); break; 
        case 3: num2[i++] = Double.parseDouble (s); break; 
       } 
       System.out.println (i + " " + typ + " " + s); 
      } 
     } 
     System.out.println("\nDONE\n"); 
    } 

    public static void main (String args[]) throws FileNotFoundException 
    { 
     Prog5Methods p5m = new Prog5Methods(); 
     p5m.readFromFile (new Scanner (new File("user.data")), 
      new String [28], 
      new int [28], 
      new char [28], 
      new double [28]); 
    } 
} 

問題1:我需要知道,每行有28個元素,並且我將它們打印上的蒼蠅,在這裏。它們被卡在匿名數組中,從未使用過,但這隻適用於簡短的演示。我可以宣佈的陣列,稍後打印:

String [] names = new String [28]; 
    int [] numbers = new int [28]; 
    char [] letters = new char [28]; 
    double [] num2 = new double [28]; 

    Prog5Methods p5m = new Prog5Methods(); 
    p5m.readFromFile (new Scanner (new File("user.data")), 
     names, numbers, letters, num2); 

我仍被綁28個元素。我可以延遲數組的初始化,直到通過讀取文件知道有多少元素。

public String [][] readFromFile (Scanner input) 
{ 
    System.out.println("\nReading from a file...\n"); 
    String [][] elems = new String [5][]; 
    for (int i = 0; i < 4; ++i) 
    { 
     elems[i] = input.nextLine().split ("[ \t]+"); 
    } 
    return elems; 
} 

public static void main (String args[]) throws FileNotFoundException 
{ 
    Prog5Methods p5m = new Prog5Methods(); 
    String [][] elems = p5m.readFromFile (new Scanner (new File("user.data"))); 

    int size = elems[0].length; 

    String [] names = new String [size]; 
    int [] numbers = new int [size]; 
    char [] letters = new char [size]; 
    double [] num2 = new double [size]; 

    for (int typ = 0; typ < 4; ++typ) 
    { 
     int i = 0; 
     for (String s: elems[typ]) 
     { 
      switch (typ) 
      { 
       case 0: names [i++] = s; break; 
       case 1: numbers[i++] = Integer.parseInt (s); break; 
       case 2: letters[i++] = s.charAt (0); break; 
       case 3: num2[i++] = Double.parseDouble (s); break; 
      } 
     } 
    } 
} 

現在既然所有的行都包含相同數量的元素,它們可能是相關的?所以一個數據集就像用戶一樣,用聲譽,代碼和xy引用來描述一些東西。在面向對象的領域,這看起來像一個對象 - 讓我們稱它爲用戶:(如果你知道C,它就像一個結構)。

我們寫一個甜美,小類:

// if we don't make it public, we can integrate it 
// into the same file. Normally, we would make it public. 

class User { 
    String name; 
    int rep; 
    char code; 
    double quote; 

    public String toString() 
    { 
     return name + "\t" + rep + "\t" + code + "\t" + quote; 
    } 

    // a constructor 
    public User (String name, int rep, char code, double quote) 
    { 
     this.name = name; 
     this.rep = rep; 
     this.code = code; 
     this.quote = quote; 
    } 
} 

,並從主方法的末尾使用它:

User [] users = new User[size]; 
    for (int i = 0; i < size; ++i) 
    { 
     users[i] = new User (names[i], numbers[i], letters[i], num2[i]); 
    } 
      // simplified for-loop and calling toString of User implicitly: 
    for (User u: users) 
     System.out.println (u); 

我不建議使用數組。一個ArrayList會更容易處理,但初學者往往被綁定到他們剛剛學到的東西,並且由於您使用Array標記了您的問題...