简体   繁体   English

从txt文件读取数组?

[英]Reading array from txt file?

This file reads from a text file that has only one line: 该文件从只有一行的文本文件中读取:

  7319812227725338960527291316

and the output is: 输出为:

Reading input values from text.txt
731
981
222
772
533
89
60
527
291
316

Question is How does the program give this output? 问题是程序如何提供此输出? I don't know how it stores 3 digits in each array cell? 我不知道它如何在每个数组单元中存储3位数字?

I also noticed that when I copy content of the txt file to Word, it pastes this 我还注意到,当我将txt文件的内容复制到Word时,它会粘贴

   7319812227725338960527291316

into a column: 列:

731
981
222
772
533
89
60
527
291
316

The text file is from my teacher. 文本文件来自我的老师。 But when I create my own text file and place a number like 123 456 789 the output makes sense since numbers in txt file are separated by space and hence each number will be assigned to an array cell. 但是,当我创建自己的文本文件并放置一个类似于123 456 789的数字时,输出是有意义的,因为txt文件中的数字由空格分隔,因此每个数字都将分配给一个数组单元。

 import java.util.Scanner;
 import java.util.Vector;
 import java.util.Arrays;
 import java.io.File;

 public class test{

 public static void main(String[] args){
    Scanner s;
    if (args.length > 0){
        try{
            s = new Scanner(new File(args[0]));
        } catch(java.io.FileNotFoundException e){
            System.out.printf("Unable to open %s\n",args[0]);
            return;
        }
        System.out.printf("Reading input values from %s.\n",args[0]);
    }else{
        s = new Scanner(System.in);
        System.out.printf("Enter a list of non-negative integers. Enter a      negative value to end the list.\n");
    }
    Vector<Integer> inputVector = new Vector<Integer>();

    int v;
    while(s.hasNextInt() && (v = s.nextInt()) >= 0)
        inputVector.add(v);

    int[] array = new int[inputVector.size()];

    for (int i = 0; i < array.length; i++){
        array[i] = inputVector.get(i);
                    System.out.println(array[i]);
            }

}

} }

The problem is the line ending character. 问题是行尾字符。 Your machine's text editor doesn't understand the line breaks inserted by your professors program. 您机器的文本编辑器无法理解您的Professors程序插入的换行符。 But your java program does check for other OS's line endings. 但是您的Java程序会检查其他OS的行尾。 That's why your Java program can actually pick up the right numbers. 因此,您的Java程序实际上可以选择正确的数字。 I'm sure you can open the text file from your teacher with a different text editor (like Sublime) that will allow you see and convert file with different line ending characters 我确定您可以使用其他文本编辑器(例如Sublime)从老师那里打开文本文件,该编辑器将允许您查看和转换具有不同行尾字符的文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM