Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/batch-file/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用java打印列表_Java_Arrays - Fatal编程技术网

用java打印列表

用java打印列表,java,arrays,Java,Arrays,我需要从一个文件中读取一些数组并打印它们。我的第一个类处理一个菜单驱动的程序,其中用户输入一个数字,告诉程序连接到文件,打印文件中的名称、整数、字符或双精度。第一件事就是连接到文件。下面是我从文件读取的不完整类: import java.util.*; public class Prog5Methods{ public Prog5Methods(){ } public void ReadFromFile(Scanner input, String [] names, int [] num

我需要从一个文件中读取一些数组并打印它们。我的第一个类处理一个菜单驱动的程序,其中用户输入一个数字,告诉程序连接到文件,打印文件中的名称、整数、字符或双精度。第一件事就是连接到文件。下面是我从文件读取的不完整类:

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

名称以数组名称[]表示,整数以数组编号[]表示,等等。我需要打印这些数组中的每个变量。

要从文本文件中读取数据,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
      }
   }
}
import java.io.*;
公共类程序5{
公共静态字符串名称[];
公共静态整数[];
公共静态字符[];
公共静态浮点小数[];
public void readFileContents(){
文件f=新文件(“yourfilename.txt”);
字节b=新字节[f.length()];
FileInputStream in=新的FileInputStream(f);
f、 改为(b);
字符串wholeFile=新字符串(b);
字符串dataArray[]=wholeFile.split(“”);
for(int i=0;i
使用
列表
而不是数组

使用扫描仪从底层流读取值

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 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);
        }
publicstaticvoidmain(字符串[]args)引发异常
{ 
.......
ArrayList name=新的ArrayList();
ArrayList编号=新的ArrayList();
ArrayList num2=新的ArrayList();
ArrayList字母=新的ArrayList();
ReadFromFile(输入、名称、数字、字母、num2);
System.out.println(名称);
系统输出打印项次(数字);
系统输出打印号(字母);
系统输出打印项数(num2);
}

您需要在文件名周围添加一个“新文件”,以创建扫描仪

  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]);
    }
}
我仍然被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;
            }
        }
    }
}
从主方法的末尾开始使用:

    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);
User[]users=新用户[size];
对于(int i=0;i

我不建议使用数组。ArrayList会更容易处理,但初学者通常会被他们刚学过的东西所束缚,而且由于您用数组标记了您的问题…

感谢您的回答,这会很有效,但我需要每种类型的变量都在一个数组中(它们已经在数组中了)我需要打印来自不同数组的每个变量。@Josh-文件的内容是什么?它是csv还是其他什么?您似乎有一些语法混乱,您正在传递一组数组作为参数,然后写入它们?如果希望文件中的数据最终出现在数组中,则需要将数组声明为静态字段?只是“静态字符串名[]”?我已经将您需要的大部分代码添加到我的答案中。你应该可以从那里得到它。你能用一个合适的方法吗?不清楚文件格式是什么。文本文件不包含数组。名字之间,整数之间真的有换行符吗?你事先知道名字的数目吗?您是否被迫使用数组?因为如果您使用数组而不知道元素的数量,那么它会更复杂(读取文件两次)。
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;
            }
        }
    }
}
// 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);