【问题标题】:Java delimiter reading a text fileJava 分隔符读取文本文件
【发布时间】:2013-08-30 18:18:32
【问题描述】:

我正在尝试读取这种格式的文本文件:

Array x
1,3,5,4

Array y
12,13,15,11

并将它放在两个数组中,但我只想要整数。 我应该使用什么分隔符来忽略字符串和空行?

这是我将 int 放入数组的代码。顺便说一句,我正在使用扫描仪来读取文件:

Scanner sc = null;

     try
     {
     sc = new Scanner(new FileInputStream("C:\\x.txt"));
     sc.useDelimiter("");  // What will I put inside a quote to get only the int values?
     }
     catch(Exception e)
     {
     System.out.println("file not found!");
     }
int[] xArray = new int[4];
int[] yArray = new int[4];

     while (sc.hasNextInt( )){
         for(int i=0; i<4; i++){
            xArray[i] = sc.nextInt( );
        }
         for(int i=0; i<4; i++){
            yArray[i] = sc.nextInt( );
        }
    }

我想得到的是

int[] xArray = {1,3,5,4}
int[] yArray = {12,13,15,11}

希望你明白:)

谢谢。

【问题讨论】:

  • 为什么不直接使用nextLine() 并使用split 方法解析每个int
  • 另外,在此期间,您在条件 while (sc.hasNextInt( )){ 中丢失了第一个 int 读取
  • 知道了!感谢您的帮助。

标签: java arrays delimiter


【解决方案1】:

我建议您使用 bufferedreader 而不是扫描仪。您可以使用以下代码:

BufferedReader br=new BufferedReader(new FileReader("your file name"));
br.readLine(); //it will omit first line Array x
String x=br.readLine(); //it return second line as a string
String[] x_value=x.split(","); //You can parse string array into int.

这是针对数组 x 的。您可以对数组 y 执行相同的操作。然后解析成int。

【讨论】:

    猜你喜欢
    • 2023-03-31
    • 2015-07-07
    • 2019-12-07
    • 1970-01-01
    • 1970-01-01
    • 2020-05-15
    • 2013-09-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多