简体   繁体   English

如何使用按行分割文本?

[英]How can I split a text using split by lines?

I am trying to split data by lines, using the method split. 我正在尝试使用split方法按行拆分数据。 This is the code i am trying to use but i can't figure out what to use for the parameters of .split(). 这是我正在尝试使用的代码,但是我无法弄清楚将什么用于.split()参数。 This is how the data will be in the txt. 这就是数据在txt中的方式。

19
23
58
49


Scanner sc = new Scanner(new File("random.txt")); 
string line = sc.nextLine(); 
String[] numbers = line.split(" "); 
int nums = new int[numbers.length]; 
for(int i=0;i<numbers.length;i++) 
nums[i] = Integer.parseInt(numbers[i]);

The end goal is so that the data can be put into an array, not to just print it. 最终目标是使数据可以放入一个数组中,而不仅仅是打印它。

You dont need to use split if you have only one number in each line. 如果每行只有一个数字,则无需使用split。

just use the following 只需使用以下

Scanner sc = new Scanner(new File("C:/projects/random.txt"));
        while( sc.hasNext()){
            System.out.println(sc.nextInt());
        }

Try to use it like this: 尝试像这样使用它:

Scanner sc = new Scanner(new File("random.txt")); Scanner sc = new Scanner(new File(“ random.txt”));

int[] nums; int [] nums;

int i=0; int i = 0;

while(sc.hasNext()){ while(sc.hasNext()){

 String line = sc.nextLine(); nums[i] = Integer.parseInt(line); i++; 

} }

Hope this helps. 希望这可以帮助。

Just as simple as that, you don't need split since you're reading line by line as @Luiggi Mendoza said 就这么简单,您不需要split因为您正在按@Luiggi Mendoza所说的逐行阅读

Scanner sc = new Scanner(new File("C:/projects/random.txt"));
while( sc.hasNext()){
    nums[i] = Integer.parseInt(numbers[i]); //They're stored in here
    i++;
}
int max = i; //To keep length of numbers that have been read
for(i = 0; i < max; i++){
    System.out.println(nums[i]); //We print them from the array
}

Try this 尝试这个

while(true){
        int tmp=line.indexOf(" ");
        if(tmp==-1)
            break;
        System.out.println(ar[i]);
        ar[i++]=Integer.parseInt(line.substring(0,tmp));
        line =line.substring(tmp+1);    
    }

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

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