开发者

Printing a list in java

I need to read a number of arrays from a file and print them. My first class handles a menu driven program where the user enters a number to tell the program to connect to the file, print the names in the file, the integers, the characters, or the doubles. The first thing I am stuck on is connecting to the file. Here is my incomplete class that reads from the file:

import java.util.*;
public class Prog5Methods{
public Prog5Methods(){
}
    public void ReadFromFile(Scanner input, String [] names, int [] numbers, char [] lette开发者_开发问答rs, 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




}

This is what the file I am reading from contains:

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

The names are in array names[], the integers are in array numbers[], etc. I need to print each variable from these arrays.


Use List<T> instead of arrays.

Read values from underlying stream using Scanner

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
            }
         }
       }
    }  
 }

Methods to parse a 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;
     } 

Test your code

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


For reading data from a text file, FileReader is your best option;

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

Would read each line from the file and print it to the standard output one line at a time.

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
      }
   }
}


You need a 'new File' around the filename, to create a Scanner,

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

To use it, you need java.io:

  import java.io.*;

If I stick to your requirements, using arrays, and Scanner, I could do something like that:

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]);
    }
}

Problem 1: I need to know, that there are 28 elements per row, and I am printing them on the fly, here. They are stuck into the anonym arrays and never used, but that's for the short demo, only. I could declare the arrays, and print later:

    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); 

I'm still bound to 28 elements. I could delay the initialization of the arrays until I know from reading the file, how much elements there are.

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

Now since all lines contain the same amount of elements, they might be related? So a dataset describes something, like a user, with reputation, code and xy-quote. In objectoriented land, this looks like an Object - let's call it user: (If you know C, it is much like a struct).

We write a sweet, little class:

// 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;
    }
}

and use it from the end of the main method:

    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);

I would not recommend using Arrays. An ArrayList would have been much easier to handle, but beginner are often bound to the things they just learned, and since you tagged your question with Array ...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜