Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/three.js/2.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_Java.util.scanner - Fatal编程技术网

在Java中的一系列数字中检测到新行

在Java中的一系列数字中检测到新行,java,java.util.scanner,Java,Java.util.scanner,假设我有一系列的数字,比如 1 2 3 4 5 6 7 8 9 0 我怎么能一步一步地通过每一个int,但当我到达一个新行时就停止了呢?我目前正在使用nextLine(),我知道nextLine()将检测新行,但我不确定如何将其组合起来。最好是整行并将字符串解析为单独的整数吗?还是有更流畅的方法 例如,我希望程序将1234,56788,90存储在各自独立的数组中 为了进一步说明,我使用的是java.util.Scanner,我正在读取一个文本文件。如果要使用Scanner,请将整行读取为

假设我有一系列的数字,比如

 1 2 3 4
 5 6 7 8
 9 0
我怎么能一步一步地通过每一个int,但当我到达一个新行时就停止了呢?我目前正在使用
nextLine()
,我知道
nextLine()
将检测新行,但我不确定如何将其组合起来。最好是整行并将字符串解析为单独的整数吗?还是有更流畅的方法

例如,我希望程序将
1234
56788
90
存储在各自独立的数组中


为了进一步说明,我使用的是
java.util.Scanner
,我正在读取一个文本文件。

如果要使用
Scanner
,请将整行读取为一个字符串,然后在字符串上构造一个扫描仪。

您可以在读取模式下打开文本文件,并使用
readLine()
方法读取整行

然后,您可以使用空格(“”)字符分割读取的行,这将自动为您提供一个数组

你可以这样做直到文件结束

import java.io.*;
class FileRead 
{
   public static void main(String args[])
  {
      try{
    // Open the file 
    FileInputStream fstream = new FileInputStream("textfile.txt");
    // Get the object of DataInputStream
    DataInputStream in = new DataInputStream(fstream);
    BufferedReader br = new BufferedReader(new InputStreamReader(in));
    String strLine;
    delimiter = " ";
    int myArr[];
    //Read File Line By Line
    while ((strLine = br.readLine()) != null)   {
      myArr = strLine.split(delimiter);
      // store this array into some global array or process it in the way you want.
    }
    //Close the input stream
    in.close();
    }catch (Exception e){//Catch exception if any
      System.err.println("Error: " + e.getMessage());
    }
  }
}

希望这能有所帮助。

“更流畅”将取决于您最终打算如何处理数据以及有多少数据。添加更多关于您正在尝试执行的操作的详细信息。您的意思是希望在一个数组中使用'1234',在另一个数组中使用'56778',依此类推?@mahendraliya:是的,没错。这就是我的意思:]这是个好主意。我从来没有想到过!太简单了!